InvokeMember where the member is an array property

2019-09-19 14:30发布

So I asked something similar last week, but I think it was pretty confusing, so Ill try to simplify it.

Say for instance I have a class that contains only properties like this:

public class MyPropertyClass
{
    public int IntegerProperty { get; set; }
}

Now suppose I have created another class with an array of MyPropertyClass like this:

public class AnotherPropertyClass
{
    public MyPropertyClass[] ArrayProperty { get; set; }
}

Now here is the complicated part. I need to dynamically create a MyPropertyClass[] somehow. I've been trying it with a List<object> thus far. Then, make a call to InvokeMember with this array. Something like this:

//The list that I am adding elements to elsewhere in the code
List<object> objList = new List<object>();

//Adding a couple elements
objList.Add(new MyPropertyClass());
objList.Add(new MyPropertyClass());

//Create the parameter object array, has to be length one and contain an
//object array casted to MyPropertyClass or it will throw an exception.
object[] ob = new object[1] { objList.ToArray() };

//Instantiate the actual object I want to assign the array to.
object obj = new AnotherPropertyClass();

//The call to InvokeMember
obj.GetType().InvokeMember(
    "ArrayProperty",
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
    Type.DefaultBinder,
    obj,
    ob);

This code will throw an exception. The problem is, objList.ToArray() creates an object[] and when InvokeMember tries to assign it to the MyPropertyClass[], it complains about the type mismatch, even though all of the elements are MyPropertyClass types. Basically what I need is a way to say, "hey, all of the elements in objList.ToArray() are going to be MyPropertyClass" i.e object{MyPropertyClass[]} while letting the actual type be arbitrary, it might not be MyPropertyClass, it could be some other type, I don't know at compile time.

What I have here is only my attempt so far, if you know a different approach i'm all ears. If you want more information, see my old question here:

runtime casting of an object[] to a custom type array

I just think there is little too much extra stuff in there that's not related to the actual problem i'm having.

标签: c# reflection
2条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-19 14:49

You can create an array of an unspecified type like this:

Array array = Array.CreateInstance(someType, someSize);
查看更多
叼着烟拽天下
3楼-- · 2019-09-19 14:55

You do it like this:

List<MyPropertyClass> objList = new List<MyPropertyClass>();
objList.Add(new MyPropertyClass());
objList.Add(new MyPropertyClass());

AnotherPropertyClass obj = new AnotherPropertyClass();

obj.GetType().GetProperty("ArrayProperty").SetValue(obj, objList.ToArray());
查看更多
登录 后发表回答