传递“类型”;到通用构造函数
下午,晚上......无论你在哪里;)
我正在开发一个“ThreadManager”,它将执行一组“ManagedThread<>”。托管线程是“ManagableThread”的通用包装器,其中包含大多数基本方法。
要启动的“ManagableThread”列表基于配置文件中的内容,并在 ThreadManager.Start 方法中生成。该列表旨在填充所有要...管理的“托管线程”。这是我尝试用来完成此任务的代码,我相信任何有能力的 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”传递给构造函数的通用参数。
Afternoon, evening... whatever it is where you are ;)
I'm working on a 'ThreadManager' that will execute a set of 'ManagedThread<>'s. A managed thread is a generic wrapper for a 'ManagableThread', which contains most of the essential methods.
The list of 'ManagableThread's to start up, is based on what comes out of a configuration file, and is generated in the ThreadManager.Start method. This list, is meant to be populated with all of the 'ManagedThread's that are to be... managed. Here is the code that I am trying to use to complete this task, and as I'm sure any competent C# developer will quickly realize - I'm not gonna swing it like this.
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;
}
}
}
I've taken a few stabs at this to no avail. If anyone has any suggestions I'd appreciate them. I'm no Generics expert, so this is slightly out of my realm of expertise, so please do refrain from making me cry, but feel free to catch me if I'm a fool.
Thanks in advance to anyone who can offer a hand.
Edit: I suppose I should clarify my issue, rather than make you all figure it out... This code will not compile as I cannot pass 'ThreadType' to the generic parameter for my constructor.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这没有道理。
泛型是编译时类型;你不能有一个直到运行时才知道的编译时类型。
相反,您需要使用反射:
That doesn't make sense.
Generics are compile-time types; you can't have a compile-time type that isn't known until runtime.
Instead, you need to use Reflection:
这是不可能的。通用参数必须在编译时已知。你的类型直到运行时才知道。
This isn't possible. Generic parameters must be known at compile time. Your type isn't known until runtime.