gpt4 book ai didi

c# - 反射 GetValue 空属性

转载 作者:行者123 更新时间:2023-12-02 01:06:54 25 4
gpt4 key购买 nike

此方法比较同一类的两个对象:

foreach (var field in fields.Where(field => !objTarget
.GetType().GetProperty(field).GetValue(objTarget, null)
.Equals(obj.GetType().GetProperty(field).GetValue(obj, null))))

如果这两个属性都有值,它可以正常工作,但有时我在这两个对象之一中有一个 null 属性,我该如何处理它?<​​/p>

编辑:如果我比较两个对象,即:

var a = new Test();
var b = new Test();
a.Property1 = "1";
b.Property1 = null;

我收到空引用异常:

An unhandled exception of type 'System.NullReferenceException' occurred in ConsoleApplication1.exe

最佳答案

而不是使用 LINQ 和 Where 方法获取变量的值并将您的条件放入循环中:

foreach (var field in fields)
{
var val1 = objTarget.GetType().GetProperty(field).GetValue(objTarget, null);
var val2 = obj.GetType().GetProperty(field).GetValue(obj, null));

if(val1 == null and val2 != null || val1 != null && !val1.Equals(val2))
{
// your code
}
}

关于c# - 反射 GetValue 空属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568000/

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