2012-01-12 70 views
0

我有一個方法有沒有辦法將未知數量的類型傳遞給C#中的泛型方法?

void InitAndLoadTables(DbConnection cnctn, Dictionary<string, DbTableLoadParameters> tableNamesAndParameters) 

其中字典可具有表的任何量。每張桌子都對應一個班級。

當我經歷了所有的表遍歷我想調用泛型方法

public void Init<T>(string tableName) 

的所有表。我試圖將該類的類屬爲DbTableLoadParameters屬性爲

Type ObjectType { get; set; } 

並在調用Init時使用該屬性。這不起作用。那麼它甚至有可能做到嗎?如果表的量將是固定我也許可以讓InitAndLoadTables一般像

InitAndLoadTables<T, K, V> 

,但事實並非如此。所以,僅僅是調用初始化其他地方一樣

Init<Orders>("Orders"); 

感謝& BR -Matti

+0

我不要以爲存在,很可能你必須傳遞一個'Type'對象的數組/集合(或者用它們的名字來代替'string's)。只有發表評論的情況下,別人可以建議 – 2012-01-12 08:34:06

+0

謝謝你的回答,但是你的意思是「很可能你必須傳遞Type對象的數組/集合(或字符串與他們的名字)」?這正是我想要做的!但它不起作用。我所知道的是,你不能將Type對象或值爲類型名稱的字符串對象傳遞給泛型方法。 – 2012-01-12 08:48:29

回答

4

沒有辦法的類型參數的任意數量傳遞到一個通用的方法,因爲通用的方法總是有一個固定的可能性類型參數的數量。

但是,你甚至不需要這樣做。有一種方法來調用一個運行時已知類型的通用方法,但這需要反思,這聽起來像它就是你真的後:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var myobj = new MyClass(); 

     // Call MyClass.Init<Orders> 
     CallMyClassInit(typeof(Orders), "tableOrders"); 

     // Call Init<string> 
     CallMyClassInit(typeof(string), "tableString"); 
    } 

    static void CallMyClassInit(MyClass obj, Type type, string tableName) 
    { 
     typeof(MyClass) 
      .GetMethod("Init") 
      .MakeGenericMethod(type) 
      .Invoke(obj, new object[] { tableName }); 
    } 
} 

class Orders { } 

class MyClass 
{ 
    public void Init<T>(string tableName) 
    { 
     Console.WriteLine("I was called with type " + typeof(T) + " for table " + tableName); 
    } 
} 

輸出:

I was called with type ConsoleApplication1.Orders for table tableOrders 
I was called with type System.String for table tableString 
+0

非常感謝!這是我所害怕的;)嘗試一下,接受它是否有效。再次感謝! – 2012-01-12 12:18:53

相關問題