Вопрос

I am using reflection to read properties from an object.

If the value I read is a reference type (for example String[]) I can cast this as Object[] array and loop through the strings in the array.

    String[] Workers = { "Steve", "Sally", "Jim" };
    Object SomeValue = Workers;
    // Prented that SomeValue is returned from reflection        
    List<Object> SomeList = new List<Object>((Object[])SomeValue);

However when the object is an array of value types I can't recast it to an array. I've tried everything. C# for some reason won't recast it as an array of ValueType (thought that would probably work).

    Int32[] WorkingHours = { 1, 2, 65, 6 };
    Object SomeValue = WorkingHours;
    // Prented that SomeValue is returned from reflection
    List<Object> SomeList = new List<Object>((ValueType[])SomeValue);

Any suggestions?

Это было полезно?

Решение

C# for some reason won't recast it as an array of ValueType (thought that would probably work).

No, it won't work because the representation is different.

The reason covariance works for reference type arrays is that the representation of a reference is the same regardless of the type of object it refers to. That's not the case if you compare value types and reference types.

For example, consider:

byte[] x = { 1, 2, 3, 4 };

Each element of x is just a byte. You can't view that array as an object[] - each element simply isn't a reference.

However, you can fairly easily convert each element via boxing and create a list that way:

List<Object> list = ((IEnumerable) WorkingHours).Cast<Object>().ToList();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top