mercredi 23 juin 2021

C# PropertyInfo.GetValue returns the concrete type

I want to query the object information, put them in my internal data types, and do some object compare later (the first thing I do is to compare the type, but I don't care about its concrete type).

//Client side
Foo a = new Foo() { Numbers = new int[3] { 1, 2, 3 } };

var r = GetCurrentProperties(a, typeof(Foo));

List<PropertyEntity> GetCurrentProperties(object objectValue, Type type)
{
    //.....
    var property = type.GetProperties()[0]; //just an example that we know the first one is IList
    object value = property.GetValue(objectValue);

    //I'm expecting value to have type of IList<int>
    Assert.True(property.PropertyType == typeof(IList<int>));
    Assert.True(value.GetType() == typeof(IList<int>)); //Error. It's an int[]...

    //...
}

It's important to notice that Type is a runtime type from the client-side. Thus I don't know what it would be at compile time. Currently, I can only think of using Convert.ChangeType to the value, but this requires the object to implement IConvertible. Is there a more elegant way?





Aucun commentaire:

Enregistrer un commentaire