[英]is there a way to pass unknown amount of types to generic method in 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
Init<Orders>("Orders");
謝謝&BR-馬蒂
無法將任意數量的類型參數傳遞給泛型方法,因為泛型方法始終具有固定數量的類型參數。
但是,您似乎根本不需要。 有一種方法可以調用運行時已知類型的通用方法,但這涉及到反射,這聽起來像是您真正想要的:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.