C# 比较C中的数据类型#
我想比较两个类的数据类型并返回bool值。问题是我的方法不比较类的类内的值 代码如下:C# 比较C中的数据类型#,c#,compare,C#,Compare,我想比较两个类的数据类型并返回bool值。问题是我的方法不比较类的类内的值 代码如下: public static class Compare { public static bool PublicInstancePropertiesEqual<T>(this T self, T to, params string[] ignore) where T : class { if (self != null && to != null)
public static class Compare
{
public static bool PublicInstancePropertiesEqual<T>(this T self, T to, params string[] ignore) where T : class
{
if (self != null && to != null)
{
var type = typeof(T);
var ignoreList = new List<string>(ignore);
var unequalProperties =
from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
where !ignoreList.Contains(pi.Name)
let selfValue = type.GetProperty(pi.Name).GetValue(self, null)
let toValue = type.GetProperty(pi.Name).GetValue(to, null)
where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue))
select selfValue;
return !unequalProperties.Any();
}
return self == to;
}
}
当您比较
Obj2
的两个实例时,res返回的值为false,只有当它们是相同的对象时,它们才会相等
要执行结构相等,您需要递归所有引用类型(即类),只需直接比较值类型(即默认使用结构相等的结构)。注int
等是值类型
我建议检查重写、实现等类型:所有表示类型有自己的equal定义的指示。在代码中,obj1.obj2和obj11.obj2的值不同,比较方法使用Object.Equals来比较类的成员,这就是Compare.PublicInstancePropertiesEqual方法返回false的原因 即:obj1.obj2=obj2;但obj11.obj2=obj22 如果希望递归比较值,则应替换该行
where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue))
与
你调试过它为什么不起作用了吗?你应该调用你自己的PublicInstancePropertiesEqual方法,而不是调用selfValue.Equals(toValue),当然你需要添加一些valuetypes检查。在这种情况下,我假设手动测试每个属性,看看哪个属性没有通过比较。然后,对于该属性,测试比较条件的3个部分中的每一个,以确定哪一个是正确的或错误的。
where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue))
where selfValue != toValue && (selfValue == null || !PublicInstancePropertiesEqual(selfValue, toValue, ignore))