是否有一种方法可以将未知数量的类型传递给C#中的泛型方法

本文关键字:类型 泛型方法 未知数 一种 方法 是否 | 更新日期: 2023-09-27 18:20:08

我有一个方法

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-Matti

是否有一种方法可以将未知数量的类型传递给C#中的泛型方法

没有办法将任意数量的类型参数传递给泛型方法,因为泛型方法总是有固定数量的类型自变量。

然而,你似乎根本不需要这个。有一种方法可以调用运行时已知类型的泛型方法,但这涉及到反射,这听起来就像是之后的

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