vendredi 2 novembre 2018

Cast property values back to original types for comparison with reflection

I'm currently trying to compare to data contracts using reflection.

The data contract represents a configuration for a virtual machine. They are both the same class type. I'm trying to log every change in the configuration when setting a new config. However, the data contracts have a large number of members. It'd be rather tedious to do it manually and it does not accommodate new data members being added later.

I tried using reflection to do it. I've managed to get the values of the data members, but depending on the actual type, comparing them will vary.

Some of the members being compared are :

  • IEnumerable<Subnets>

  • IEnumerable<IP Address>

  • X509Certificates

  • Enums

and a few more

I'm trying to find a way to cast the property to it's actual class, but everything I've found thus far has failed to work.

Here is an example of what I've done so far with reflection.

ExampleClass firstExample = new ExampleClass("a", 1);
ExampleClass secondExample = new ExampleClass("a", 2);
List<string> exampleList = new List<string>()
{
    "a",
    "b"
};

firstExample.ValueThree = exampleList;
secondExample.ValueThree = exampleList;

firstExample.FourthValue = new List<string>()
{
    "c",
    "d"
};

secondExample.FourthValue = new List<string>()
{
    "c",
    "d"
};

Type exampleType = firstExample.GetType();

foreach (PropertyInfo item in exampleType.GetProperties())
{
    var firstExampleValue = item.GetValue(firstExample);
    var secondExampleValue = item.GetValue(secondExample);
    string propName = item.Name;

    bool areEqual = firstExampleValue.Equals(secondExampleValue);

    Console.WriteLine(propName);
    Console.WriteLine(string.Format("\nFirst Value : {0}\nSecond Value : {1}", firstExampleValue, secondExampleValue));
    Console.WriteLine(string.Format("Values are equal : {0}\n\n", areEqual));
}

Is there a practical way to convert these to there actual classes as defined by the data contract? I've looked into Convert.ChangeType but found that this will not work for a good portion of the members as they are not IConvertable.

Thanks,

Edwin





Aucun commentaire:

Enregistrer un commentaire