gpt4 book ai didi

.net - .NET 类的类似结构的深层 Equals()?

转载 作者:行者123 更新时间:2023-12-04 07:07:40 26 4
gpt4 key购买 nike

鉴于其中不包含引用循环的两个对象,您是否知道一种以“通用”方式(通过反射)测试它们相等性的方法?

我基本上想要与结构等价相同的语义,只在类上。

最佳答案

我认为框架中没有这样的方法可用,但它很容易编写。也许不是最短的实现,但似乎可以完成这项工作:

private bool AreEqual(object x, object y)
{
// if both are null, they are equal
if (x == null && y == null)
{
return true;
}
// if one of them are null, they are not equal
else if (x == null || y == null)
{
return false;
}

// if they are of different types, they can't be compared
if (x.GetType() != y.GetType())
{
throw new InvalidOperationException("x and y must be of the same type");
}

Type type = x.GetType();
PropertyInfo[] properties = type.GetProperties();

for (int i = 0; i < properties.Length; i++)
{
// compare only properties that requires no parameters
if (properties[i].GetGetMethod().GetParameters().Length == 0)
{
object xValue = properties[i].GetValue(x, null);
object yValue = properties[i].GetValue(y, null);

if (properties[i].PropertyType.IsValueType && !xValue.Equals(yValue))
{
return false;
}
else if (!properties[i].PropertyType.IsValueType)
{
if (!AreEqual(xValue, yValue))
{
return false;
}
} // if
} // if
} // for

return true;

}

关于.net - .NET 类的类似结构的深层 Equals()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/874295/

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