Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

c# - InvokeMember where the member is an array property with reflection

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Array array = Array.CreateInstance(someType, someSize);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...