2015-10-15 29 views
0

我想這樣做:如何使用類型變量作爲循環中的類型參數?

foreach(Type t in Aplicables) 
{ 
    filename = Path.Combine(dataDir, t.Name + "s.txt"); 
    tempJson = JsonConvert.SerializeObject(DataRef<t>.DataList.ToArray()); 
    System.IO.File.WriteAllText(filename, tempJson); 
} 

但我不能。

我知道它與編譯有關。就像編譯器需要明確告訴運行時間之前將使用哪種類型一樣。沒關係。但我寧願在循環中執行此操作,而不必爲每個「Aplicables」的每個成員手動輸入它。

有沒有辦法做到這一點?

BTW

public struct DataRef<T> 
{ 
    public int RefNum; 
    public static List<T> DataList = new List<T>(); 

    public T value 
    { 
     get 
     { 
      return DataList[RefNum]; 
     } 
    } 

} 
+1

你可以與反思這樣做,但不是靜態。請參見['Type.MakeGenericType(Type [])'](https://msdn.microsoft.com/en-us/library/system.type.makegenerictype(v = vs.110).aspx) – Mitch

+0

什麼是'Aplicables '和'DataRef'在這個上下文中? – Dai

+0

「應用程序」是一個列表和「DataRef 」包含一個靜態列表稱爲DataList –

回答

0

你需要做這樣的事情:

foreach (Type t in Aplicables) 
{ 
    filename = Path.Combine(dataDir, t.Name + "s.txt"); 
    var prop = typeof(DataRef<>).MakeGenericType(t).GetProperty("DataList"); 
    var dataList = prop.GetValue(null) as //List<int> or whatever your dataList is; 
    tempJson = JsonConvert.SerializeObject(dataList.ToArray()); 
    System.IO.File.WriteAllText(filename, tempJson); 
} 
+0

對不起,我忘了包括之前的「dataRef」定義。正如你所看到的,「DataList」也是通用的 –

相關問題