如果泛型类型参数直到运行时才未知,如何调用静态泛型类方法? [英] How to invoke static generic class methods if the generic type parameters are unknown until runtime?

查看:53
本文介绍了如果泛型类型参数直到运行时才未知,如何调用静态泛型类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个静态的泛型类.直到运行时,它的通用类型参数才可用.如何调用其成员?

Assume I have a static generic class. Its generic type parameters are not available until runtime. How to invoke its members?

请参见以下代码段:

static class Utility<T>
{
    public static void DoSomething() { }
}   

class Tester
{
    static Type GetTypeAtRuntime()
    {
      // return an object of type Type at runtime.
    } 
    static void Main(string[] args)
    {


        Type t = GetTypeAtRuntime();

        // I want to invoke Utility<>.DoSomething() here. How to do this?

    }
}

好的,这是基于下面两个人给出的答案的解决方案.谢谢你们两个!

OK, this is the solution based on the responses given by two guys below. Thanks for both of you!

 static class Utility<T>
{
    //Trivial method
    public static void DoSomething(T t) { Console.WriteLine(t.GetType()); }
}

// assume Foo is unknown at compile time.
class Foo { }

class Tester
{

    static void Main(string[] args)
    {

        Type t = typeof(Foo);// assume Foo is unknown at compile time.

        Type genType = typeof(Utility<>);

        Type con = genType.MakeGenericType(new Type[] { t });

        MethodInfo mi = con.GetMethod("DoSomething", BindingFlags.Static | BindingFlags.Public);

        mi.Invoke(null, new object[] { Activator.CreateInstance(t) });

    }
}

推荐答案

然后,您将需要使用反射来获取方法并调用它.如果要声明该类型的对象,则需要在编译时解析泛型类型参数:

Then you'll need to use reflection to get the method and invoke it. Generic type arguments needs to be resolved compile time if you are going to declare an object of that type:

Type t= GetTypeAtRuntime();;
var doSomething = typeof(List<>).MakeGenericType(t).GetMethod("DoSomething", BindingFlags.Static | BindingFlags.Public);
doSomething.Invoke(null, new object[] { });

但是在您的示例中,方法签名或实现中未使用T,如果是这种情况,我会将其移至非通用基类.

However in your example T is not used in the method signature or implementation and if that's the case I'd move it to a non-generic base class.

免责声明:建议的解决方案仅意味着,如果您确实愿意,则可以执行此操作,但是从示例中看来,mpore就像是一个设计问题.我建议在这种情况下重新使用静态/泛型

DISCLAIMER: the suggested solution is only meant as a you can do this if you really want to but from the example it seems mpore like an issue of the design. I'd suggest revisiting the use of static/generic in this case

这篇关于如果泛型类型参数直到运行时才未知,如何调用静态泛型类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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