Comparing two values from GetValue reflection method
I am getting value1
and value2
which are both zero as not equal when they should be the same.
How else can I compare the values of these 2 objects?
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;
}
They are objects, so you should use value1.Equals(value2)
with checking if value1
is not null
EDIT: Better: use static Object.Equals(value1, value2)
(credits to @LukeH)
Equals is inherited from System.Object and it won't ensure that both objects would be correctly compared if you don't provide your own implementation of Equals.
Override System.Object.Equals and/or implement IEquatable<T>
in your domain objects or any object you want to eval its equality with another one.
Learn more reading this article:
- https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1.equals?view=netcore-3.1
Swap if (value1 != value2)
for if (!object.Equals(value1, value2))
and you should be good to go.
The !=
operator that you're currently using is non-virtual, and since the compile-time type of the GetValue
calls is object
you'll always be testing for reference (in)equality.
Using the static object.Equals(x,y)
method instead tests first for reference equality, and if the objects aren't the same reference will then defer to the virtual Equals
method.
If the type of the property is a value type (like int for example), the value returned by GetValue will be boxed into an object. Then ==
will compare the references of these boxed values. If you want to have a correct comparison, you should use the Equals method:
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
}
}
精彩评论