samedi 16 mai 2015

How can I compare value-types acquired from Reflection's "GetValue"?

I have this code which gets the value from the Test class and then converts it to the type it is. It prints correctly as "Int32" but when I test the equality with another variable with the same value, it prints "false". I suspect it is because it is testing reference equality and that the 2 variables are really still objects. Is there any way to compare them, keeping in mind I won't know the type of the value returned until runtime (it could be a string, float, other class, etc.)?

class Test{public int y;}

static void Main()
{
    var test1 = new Test{y=1};
    var test2 = new Test{y=1};
    var fields = test1.GetType().GetFields();
    var test1Value = fields[0].GetValue(test1);
    var test2Value = fields[0].GetValue(test2);
    var test1Converted = Convert.ChangeType(test1Value, test1Value.GetType());
    var test2Converted = Convert.ChangeType(test2Value, test2Value.GetType());
    Console.WriteLine(test1Converted); // prints Int32
    Console.WriteLine(test1Converted == test2Converted); // prints false
}





Aucun commentaire:

Enregistrer un commentaire