猿问

使用仅在执行时知道的类型参数调用泛型方法

使用仅在执行时知道的类型参数调用泛型方法

编辑:

当然,我的真实代码看起来并不完全像这样。我试着编写半伪代码,以便更清楚地表达我想做的事情。

看起来它只是把事情搞砸了。

所以,我真正想做的是:

Method<Interface1>();Method<Interface2>();Method<Interface3>();...

嗯......我想也许我可以用反射把它变成一个循环。所以问题是:我该怎么做。我有反射的浅识。所以代码示例会很棒。

场景如下所示:

public void Method<T>() where T : class{}public void AnotherMethod(){
    Assembly assembly = Assembly.GetExecutingAssembly();

    var interfaces = from i in assembly.GetTypes()
    where i.Namespace == "MyNamespace.Interface" // only interfaces stored here
    select i;

    foreach(var i in interfaces)
    {
        Method<i>(); // Get compile error here!
    }




原帖:

嗨!

我正在尝试遍历命名空间中的所有接口,并将它们作为参数发送到这样的泛型方法:

public void Method<T>() where T : class{}public void AnotherMethod(){
    Assembly assembly = Assembly.GetExecutingAssembly();

    var interfaces = from i in assembly.GetTypes()
    where i.Namespace == "MyNamespace.Interface" // only interfaces stored here
    select i;

    foreach(var interface in interfaces)
    {
        Method<interface>(); // Get compile error here!
    }}

我得到的错误是“预期输入名称,但找到了本地变量名称”。如果我试试

...
    foreach(var interface in interfaces)
    {
        Method<interface.MakeGenericType()>(); // Still get compile error here!
    }}

我得到“不能将运算符'<'应用于'方法组'和'System.Type'类型的操作数”“如何解决这个问题?


弑天下
浏览 460回答 2
2回答

吃鸡游戏

请注意,您可能会遇到“方法分辨率中的模糊匹配”&nbsp;GetMethod()。当您尝试获取的方法有一些重载时会发生这种情况。所以,你需要指定要使用你想要哪一个GetMethod("Name", new Type[] {arguments})
随时随地看视频慕课网APP
我要回答