繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM