[英]Passing a 'Type' to a Generic Constructor
下午,晚上……无论您在哪里;)
我正在使用“ ThreadManager”,它将执行一组“ ManagedThread <>”。 托管线程是“ ManagableThread”的通用包装,其中包含大多数基本方法。
要启动的“ ManagableThread”列表基于配置文件中的内容,并在ThreadManager.Start方法中生成。 该列表旨在填充将要管理的所有“ ManagedThread”。 这是我要用来完成此任务的代码,并且我确定任何有能力的C#开发人员都会很快意识到-我不会像这样摇摆它。
public void Start() {
foreach (String ThreadName in this.Config.Arguments.Keys) {
Type ThreadType = null;
if ((ThreadType = Type.GetType(ThreadName)) == null) {
continue;
}
else {
ManagedThread<ThreadType> T = new ManagedThread<ThreadType>(
this,
this.GetConfiguration(ThreadType)
);
this.ManagedThreads.Add(T);
continue;
}
}
}
我对此采取了一些努力,但没有成功。 如果有人有任何建议,我将不胜感激。 我不是泛型专家,所以这有点超出我的专业领域,所以请不要让我哭泣,但是如果我是傻瓜,请随时抓住我。
在此先感谢任何可以提供帮助的人。
编辑:我想我应该澄清我的问题,而不是让所有人都知道...由于无法将'ThreadType'传递给构造函数的通用参数,因此该代码将无法编译。
这没有意义。
泛型是编译时类型; 您不能拥有直到运行时才知道的编译时类型。
相反,您需要使用Reflection:
Type gt = typeof(ManagedThread<>).MakeGenericType(ThreadType);
object t = Activator.CreateInstance(gt, this,this.GetConfiguration(ThreadType));
这是不可能的。 泛型参数必须在编译时已知。 在运行时才知道您的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.