Skip to main content
 首页 » 编程设计

c#之如果泛型类型参数在运行时未知,如何调用静态泛型类方法

2024年02月24日22insus

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

请看下面的代码片段:

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? 
 
    } 
} 

编辑:

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

 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) }); 
 
    } 
} 

请您参考如下方法:

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

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

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

免责声明:建议的解决方案仅表示您可以在确实需要时执行此操作,但从示例来看,这似乎更像是设计问题。在这种情况下,我建议重新审视静态/泛型的使用