0

我想做类似的事情

public class someClass{

    public void somemethod<T>(){ 
        //dosomething with T;
    }

     public void someothermethod<U>(){ 
        //dosomething with U;
    }
}

同时在另一个班级

IDictionary<Type,Type> dic = new Dictionary<Type, Type>();
dic.add(ClassA, InterfaceA);
dic.add(ClassB, InterfaceB);
dic.add(ClassC, InterfaceC);
dic.add(ClassD, InterfaceD);

dic.foreach(kvp => somemethod<kvp.key>().someothermethod<kvp.value>());

这似乎不起作用。在尖括号内,Visual Studio 告诉我它无法解析 kvp?我究竟做错了什么?任何帮助或示例总是受到赞赏。

4

1 回答 1

3

这根本不是关于字典的——它是关于在执行时只知道类型时调用泛型方法。

您可以通过反射来做到这一点,使用MethodInfo.MakeGenericMethod,然后调用结果:

using System;
using System.Reflection;

class Test
{
    static void Main()
    {
        InvokeGenericMethod(typeof(string));
        InvokeGenericMethod(typeof(int));
    }

    static void InvokeGenericMethod(Type type)
    {
        var method = typeof(Test).GetMethod("GenericMethod");
        var generic = method.MakeGenericMethod(type);
        generic.Invoke(null, null);
    }

    public static void GenericMethod<T>()
    {
        Console.WriteLine("typeof(T) = {0}", typeof(T));
    }    
}
于 2012-05-18T19:27:01.143 回答