调用带有可变型泛型方法 [英] Calling generic method with Type variable

查看:105
本文介绍了调用带有可变型泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的方法

Foo<T>

我有一个类型变量

是否有可能实现的东西像美孚&LT;酒吧和GT;

Is it possible to achieve something like Foo<bar>

Visual Studio是期待在酒吧类型或命名空间。

Visual studio is expecting a type or namespace at the bar.

善良,

推荐答案

让我们假设foo是课堂测试中声明,如

Lets assume that Foo is declared in class Test such as

public class Test
{
   public void Foo<T>() { ... }

}

您需要先初始化方法键入使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx\">MakeGenericMethod.然后使用反射调用它。

You need to first instantiate the method for type bar using MakeGenericMethod. And then invoke it using reflection.

var mi = typeof(Test).GetMethod("Foo");
var fooRef = mi.MakeGenericMethod(bar);
fooRef.Invoke(new Test(), null);

这篇关于调用带有可变型泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆