gog*_*gog 2 .net c# null system.reflection
此方法比较同一类的两个对象:
foreach (var field in fields.Where(field => !objTarget
.GetType().GetProperty(field).GetValue(objTarget, null)
.Equals(obj.GetType().GetProperty(field).GetValue(obj, null))))
Run Code Online (Sandbox Code Playgroud)
如果这两个属性都有它正常工作的值,但有时我在这两个对象之一中有一个空属性,我该如何处理?
编辑:如果我比较两个对象,即:
var a = new Test();
var b = new Test();
a.Property1 = "1";
b.Property1 = null;
Run Code Online (Sandbox Code Playgroud)
我得到空引用异常:
ConsoleApplication1.exe 中发生类型为“System.NullReferenceException”的未处理异常
而不是使用 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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11678 次 |
| 最近记录: |