[英]Comparing two values from GetValue reflection method
我得到的value1
和value2
都为零,因为它们应该相同时不相等。
我还能如何比较这两个对象的值?
private bool CheckProjectIsUnique(
TBR.Domain.Project project,
List<UniqueProjectType> types,
out UniqueProjectType uniqueCandidate)
{
uniqueCandidate = CreateUniqueProjectType(project);
if (types.Count == 0)
return true;
foreach (UniqueProjectType type in types)
{
bool exists = true;
foreach (PropertyInfo prop in type.GetType().GetProperties())
{
var value1 = prop.GetValue(type, null);
var value2 = prop.GetValue(uniqueCandidate, null);
if (value1 != value2)
{
exists = false;
break;
}
}
if (exists)
return true;
}
return false;
}
它们是对象,因此您应该使用value1.Equals(value2)
来检查value1
是否不为null
编辑:更好:使用静态Object.Equals(value1, value2)
(归功于@LukeH)
Equals 是从 System.Object 继承的,如果您不提供自己的 Equals 实现,它将无法确保正确比较两个对象。
覆盖 System.Object.Equals 和/或在您的域对象或您想要评估其与另一个对象的相等性的任何对象中实现IEquatable<T>
。
阅读本文了解更多信息:
将if (value1 != value2)
交换为if (!object.Equals(value1, value2))
就可以了。
您当前使用的!=
运算符是非虚拟的,并且由于GetValue
调用的编译时类型是object
您将始终测试引用(不)相等性。
使用静态object.Equals(x,y)
方法首先测试引用相等性,如果对象不是相同的引用,则将遵循虚拟Equals
方法。
如果属性的类型是值类型(例如 int),则 GetValue 返回的值将被装箱到一个对象中。 然后==
将比较这些装箱值的引用。 如果你想有一个正确的比较,你应该使用 Equals 方法:
class Program
{
class Test
{
public int A { get; set; }
}
static void Main(string[] args)
{
var testA = new Test { A = 1 };
var testB = new Test { A = 1 };
var propertyInfo = typeof(Test).GetProperties().Where(p => p.Name == "A").Single();
var valueA = propertyInfo.GetValue(testA, null);
var valueB = propertyInfo.GetValue(testB, null);
var result = valueA == valueB; // False
var resultEquals = valueA.Equals(valueB); // True
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.