2012-12-17 27 views
-1

所以我上週提出了類似的問題,但我認爲它很混亂,所以我試圖簡化它。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

我只是認爲這是在那裏,這不是與我遇到的實際問題,一點也不爲過額外的東西。

+0

這甚至不編譯... –

+0

改變'obj.InvokeMember 'to'obj.GetType()。InvokeMember'和兩個'add()'方法到'Add()'將會修復它。 – Mir

+0

@TrevorPilley我沒有複製和粘貼,因爲我的代碼比這個示例複雜得多。我向你保證它會帶來一點欺騙。 –

回答

3

您可以創建一個未指定類型的像這樣的數組:

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

但是當我嘗試使用該變量調用InvokeMember時會發生什麼? –

+1

@MattGrogan:它會起作用,因爲變量的類型是正確的。 – SLaks

+0

關於這種方法的問題:它創建一個2D數組? 此外,它不工作,因爲當我調用SetValue時,它抱怨它不能分配一個對象到這種類型的數組(或類似的東西)。 –

1

你不喜歡這樣:

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()); 
+0

這會拋出一個ArgumentException異常,記住obj和objList仍然只是對象類型,我不知道在編譯時它們實際上是AnotherPropertyClass,它可能是別的東西。 –

相關問題