gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:53:57 25 4
gpt4 key购买 nike

我有以下静态类

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

在其他地方,我有一个 System.Type 变量,我需要将其作为通用类型参数传入,理想情况下:

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

我知道可以通过反射返回 MyFoo 的实例(如果我将其设为非静态),但这并不理想。无论如何将类型作为通用类型参数传递给 MyFoo 静态类?

最佳答案

做不到。第二个示例中 type 变量的值仅在运行时 时已知。第一个示例中的T 类型参数必须编译时 解析。

相反,请查看 Activator.CreateInstance() .

关于c# - 将类型变量作为通用类型参数传递给静态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19505931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com