【问题标题】:How should I call the generic function without knowing the type at compile time?我应该如何在编译时不知道类型的情况下调用泛型函数?
【发布时间】:2010-08-24 09:20:02
【问题描述】:

可以说,如果我遇到以下情况。


Type somethingType = b.GetType();
    // b is an instance of Bar();

Foo<somethingType>(); //Compilation error!!
    //I don't know what is the Type of "something" at compile time to call
    //like Foo<Bar>();


//Where:
public void Foo<T>()
{
    //impl
}

编译时不知道类型怎么调用泛型函数?

【问题讨论】:

标签: c# generics


【解决方案1】:

你需要使用反射:

MethodInfo methodDefinition = GetType().GetMethod("Foo", new Type[] { });
MethodInfo method = methodDefinition.MakeGenericMethod(somethingType);
method.Invoke();

在编写泛型方法时,最好尽可能提供非泛型重载。例如,如果Foo&lt;T&gt;() 的作者添加了Foo(Type type) 重载,则此处不需要使用反射。

【讨论】:

  • 更正一点:MethodInfo method = methodDefinition.MakeGenericMethod(somethingType);
  • 谢谢,已更正。这个肯定漏掉了我的 Stack Overflow 单元测试套件。
  • ?如果函数“Foo()”是该类型的扩展方法怎么办。它会在 MethodInfo[] 中列出吗?还是 GetMethod(..)?
  • 不,这将是任何定义扩展方法的类的静态方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
相关资源
最近更新 更多