简体   繁体   English

将类型变量作为通用类型参数传递给静态类

[英]Passing Type variable as Generic Type Parameter to Static Class

I have the following static class 我有以下静态课程

public static class MyFoo<T> where T : class
{
    public static IBar<T> Begin()
    {
        return new Bar<T>();
    }
}

Elsewhere, I have a variable of System.Type, which I need to pass in as the Generic Type argument, ideally: 在其他地方,我有一个System.Type变量,最好将它作为Generic Type参数传递给我:

public void MyFunction(Type type)
{
     MyFoo<type>.Begin();
}

I know its possible through reflection to return an instance of MyFoo (If i make it non static) but this would not be ideal. 我知道通过反射可以返回MyFoo的实例(如果我使它成为非静态的),但这不是理想的。 Is there anyway to pass type as a Generic Type argument to the MyFoo static class? 无论如何,有没有将类型作为通用类型参数传递给MyFoo静态类?

Can't do it. 做不到 The value of the type variable in the second sample is only known at run time . 仅在运行时才知道第二个样本中type变量的值。 The T type parameter in the first sample must be resolved at compile time . 必须编译时解析第一个样本中的T类型参数。

Instead, look into Activator.CreateInstance() . 相反,请查看Activator.CreateInstance()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM