Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...