所以我上週提出了類似的問題,但我認爲它很混亂,所以我試圖簡化它。InvokeMember其中成員是一個具有反射的數組屬性
例如說我有一個包含屬性只有像這樣的類:
public class MyPropertyClass
{
public int IntegerProperty { get; set; }
}
現在假設我已經創建了另一個類的MyPropertyClass
數組是這樣的:
public class AnotherPropertyClass
{
public MyPropertyClass[] ArrayProperty { get; set; }
}
現在,這裏是複雜的部分。 我需要動態地創建一個MyPropertyClass[]
莫名其妙。到目前爲止,我一直在嘗試使用List<object>
。然後,用這個數組撥打InvokeMember
。像這樣:
//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);
此代碼將引發異常。問題是,objList.ToArray()創建object[]
,並且當InvokeMember嘗試將其分配給MyPropertyClass[]
時,它會抱怨類型不匹配,即使所有元素都是MyPropertyClass
類型。基本上我需要的是這樣一種說法,「嘿,objList.ToArray()中的所有元素都將是MyPropertyClass
」即object {MyPropertyClass []},同時讓實際類型是任意的,它可能不是MyPropertyClass
,它可能是其他類型的,我不知道在編譯時。
我在這裏的只是我的嘗試到目前爲止,如果你知道一個不同的方法我耳熟能詳。如果您想了解更多信息,請參閱我的老問題在這裏:
runtime casting of an object[] to a custom type array
我只是認爲這是在那裏,這不是與我遇到的實際問題,一點也不爲過額外的東西。
這甚至不編譯... –
改變'obj.InvokeMember 'to'obj.GetType()。InvokeMember'和兩個'add()'方法到'Add()'將會修復它。 – Mir
@TrevorPilley我沒有複製和粘貼,因爲我的代碼比這個示例複雜得多。我向你保證它會帶來一點欺騙。 –