gpt4 book ai didi

c# - Lambda 用于查找属性的差异,反射在 C# 中未正确返回

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:31 25 4
gpt4 key购买 nike

我正在尝试根据其他一些帖子解决问题。我正在查看列表中具有相同属性的多个对象,我需要验证它们在每个对象中的值是否相同。如果不是,我需要标记对象具有冲突的属性值。我正在尝试并且虽然可行的代码在下面,但始终返回 true 以将属性添加到列表中,即使列表项中的值都相同也是如此。

public List<string> JobHasConflictingTaxForms(Job job, List<string> propertiesToCheck)
{
var conflictingPropertiesList = new List<string>();

foreach(string prop in propertiesToCheck)
{
if (!job.TaxForms.TrueForAll(t => t.ARecord.GetType().GetProperty(prop)
.GetValue(t.ARecord, null) ==
job.TaxForms[0].ARecord.GetType().GetProperty(prop)
.GetValue(job.TaxForms[0].ARecord, null)))
{
conflictingPropertiesList.Add(prop);
}
}

return conflictingPropertiesList;
}

每个税单都有一个对象作为属性,称为“ARecord”。这些是我需要验证的属性对于每个税表都是普遍相同的,如果不是,那么我需要标记其中一个是不同的。我错过了什么,或者这个 lambda 语句做错了什么?即使我具有所有相同的值,或者具有相同值的三种形式,以及一种具有不同属性的形式,它也会返回相同的结果。它总是返回 true。

附言我也尝试过使用 Any(i => logic != other item)。但是没有按照我的预期工作。

TaxForm 类

 public class TaxForm 
{
#region Properties

public string TaxFormType
{
get;
set;
}

public string FileName
{
get;
set;
}

public string FileFullName
{
get;
set;
}

public bool ShouldProcess
{
get;
set;
}

public bool Corrected
{
get;
set;
}

public TRecord TRecord
{
get;
set;
}

public ARecord ARecord
{
get;
set;
}

public BRecord BRecord
{
get;
set;
}

public List<string> BRecords
{
get;
set;
}

public bool HasConflictingrecords
{
get;
set;
}

public bool HasDataConflict
{
get;
set;
}

#endregion

现在是 ARecord 类

public class ARecord
{
#region Properties
/// <summary>
/// Found at POS(12) for 8
/// </summary>
public string PayerTIN
{
get;
set;
}

/// <summary>
/// Found at POS(38) for 39.
/// </summary>
public string PayerName
{
get;
set;
}

/// <summary>
/// Found at POS(134) for 39.
/// </summary>
public string PayerAddress
{
get;
set;
}

/// <summary>
/// found at POS(255) for 14.
/// </summary>
public string PayerPhone
{
get;
set;
}

/// <summary>
/// Found at POS(2) for 3.
/// </summary>
public string PayerYear
{
get;
set;
}

#endregion


}

最佳答案

PropertyInfo.GetValue 方法返回它引用的属性的值作为 Object 类型。执行的 == 运算符是针对 Object 类的,而不是针对 String 的。

要执行正确的比较方法,您需要将调用 PropertyInfo.GetValue 的返回值转换为 string,然后使用 == 运算符或调用静态 string.Equals 方法。

关于c# - Lambda 用于查找属性的差异,反射在 C# 中未正确返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25510739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com