[英]If a class has a property of another class, how to tell if the properties of the inner class match
我正在研究一種能夠查看 2 個對象是否匹配的解決方案。 重要的是,對於 2 個對象,如果它們共享一個屬性,則這些屬性的值是匹配的
對於兩個類 SC 和 DI,Test 屬性正確地評估為 True。 但是 Little 類將評估為假,因為 SC 和 DI 使用 Little 對象的不同實例,即使 Little 類的信息是正確的。
namespace HelloWorld
{
using System;
using System.Reflection;
public class Little
{
public string L1 { get; set; }
public string L2 { get; set; }
}
public class Solution
{
public string Name { get; set; }
public string Test { get; set; }
public Little L {get; set; }
}
public class Device
{
public string Name { get; set; }
public string Test { get; set; }
public Little L {get; set; }
}
public class Program
{
static void Main(string[] args)
{
var Li = new Little {
L1 = "L1111",
L2 = "L2222"
};
var Li2 = new Little {
L1 = "L1111",
L2 = "L2222"
};
var SC = new Solution {
Name = "SC",
Test = "T1",
L = Li2
};
var DI = new Device {
Name = "DI",
Test = "T1",
L = Li
};
foreach (var property in SC.GetType().GetProperties())
{
var deviceProperty = DI.GetType().GetProperty(property.Name);
if (deviceProperty != null)
{
if (deviceProperty.GetValue(DI) != property.GetValue(SC))
{
// it is registered as flase since DI and SC have different Little objects - even though thouse object values are the same
// Best way to determine if the values are of type Little (or any other me-defined class) - because wont .IsClass evaluate string to True as well?
// What if there was another class inside Litte? Do I have to recursively / loop until I can see everything is a string or int?
}
else
{
Console.WriteLine("We have a match");
}
}
}
}
}
}
GetValue 返回一個object
,調用 ToString() 然后進行“字符串比較”。 實際上,您的代碼比較了兩個對象,因此不匹配。 如果您期望不同類型的屬性,那么您需要重寫Equals
來進行自定義比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.