Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

c# - 如何使用反射调用泛型方法?(How do I use reflection to call a generic method?)

What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?

(当类型参数在编译时未知,而是在运行时动态获取时,调用通用方法的最佳方法是什么?)

Consider the following sample code - inside the Example() method, what's the most concise way to invoke GenericMethod<T>() using the Type stored in the myType variable?

(考虑以下示例代码-在Example()方法内部,使用存储在myType变量中的Type调用GenericMethod<T>()的最简洁方法是什么?)

public class Sample
{
    public void Example(string typeName)
    {
        Type myType = FindType(typeName);

        // What goes here to call GenericMethod<T>()?
        GenericMethod<myType>(); // This doesn't work

        // What changes to call StaticMethod<T>()?
        Sample.StaticMethod<myType>(); // This also doesn't work
    }

    public void GenericMethod<T>()
    {
        // ...
    }

    public static void StaticMethod<T>()
    {
        //...
    }
}
  ask by Bevan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(在类型推断不可用的情况下(例如问题中的确切示例),它无济于事。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...