[英]Reflection GetValue null property
此方法比較同一類的兩個對象:
foreach (var field in fields.Where(field => !objTarget
.GetType().GetProperty(field).GetValue(objTarget, null)
.Equals(obj.GetType().GetProperty(field).GetValue(obj, null))))
如果兩個屬性都有值,則可以正常工作,但有時我在這兩個對象之一中具有空屬性,我該如何處理呢?
編輯:如果即時通訊比較兩個對象,即:
var a = new Test();
var b = new Test();
a.Property1 = "1";
b.Property1 = null;
即時通訊獲取空引用異常:
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.