You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod :
(您需要使用反射来使方法开始,然后通过为MakeGenericMethod提供类型参数来“构造”它:)
MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
For a static method, pass null
as the first argument to Invoke
.
(对于静态方法,将null
作为第一个参数传递给Invoke
。)
That's nothing to do with generic methods - it's just normal reflection. (这与泛型方法无关,只是正常的反映。)
As noted, a lot of this is simpler as of C# 4 using dynamic
- if you can use type inference, of course.
(如前所述,从C#4开始,使用dynamic
很多事情都比较简单-当然,如果可以使用类型推断。)
It doesn't help in cases where type inference isn't available, such as the exact example in the question. (在类型推断不可用的情况下(例如问题中的确切示例),它无济于事。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…