通用方法是......
public void PrintGeneric2<T>(T test) where T : ITest
{
Console.WriteLine("Generic : " + test.myvar);
}
我是从Main()...
调用的 Type t = test2.GetType();
PrintGeneric2<t>(test2);
我收到错误“CS0246:无法找到类型或命名空间名称't'和”CS1502:最佳重载方法匹配DoSomethingClass.PrintGeneric2&lt; t&gt;(T)具有无效参数“
这与我之前的问题有关:C# : Passing a Generic Object
我已经读过,如果没有使用reflection或methodinfo,就无法在运行时确定泛型类型,但在这种情况下,我不太清楚如何这样做。
谢谢你能开导我=)
答案 0 :(得分:27)
如果您真的想使用编译时未知的类型参数调用泛型方法,可以编写如下内容:
typeof(YourType)
.GetMethod("PrintGeneric2")
.MakeGenericMethod(t)
.Invoke(instance, new object[] { test2 } );
但是,正如其他回复所述,泛型可能不是您的最佳解决方案。
答案 1 :(得分:6)
泛型提供编译时间参数多态。您尝试使用仅在运行时指定的类型。 简短的回答:它不起作用,没有理由(除了反思,但完全是一个不同的野兽)。
答案 2 :(得分:0)
请致电:
PrintGeneric2(test2);
编译器会根据您传递的内容推断<t>
。