【发布时间】:2009-10-16 17:48:54
【问题描述】:
考虑以下代码:
public class SystemManager<T> where T : ISettings
{
public SystemManager()
{
T implicit1 = default(T);
T implicit2 = default(T);
if (implicit1 != implicit2)
{
// This will not compile saying the compiler cannot compare
// using '!=' two objects of type 'T' and 'T'
}
ISettings explicit1 = null;
ISettings explicit2 = null;
if (explicit1 != explicit2)
{
// This will compile fine
}
}
}
在上面,编译器知道 T 是 ISettings,那么为什么比较只在泛型范围之外起作用呢?这会成为“.NET 4 就是答案”的事情之一吗?
编辑:
在回答 Manu 的问题时,为什么直接使用泛型而不是 ISettings。
假设如下:
void Main()
{
SystemManager<XmlSettings> manager = new SystemManager<XmlSettings>();
// I want to disallow the following
SystemManager<RegistrySettings> manager = new SystemManager<RegistrySettings>();
}
public interface ISettings
{
}
public class XmlSettings : ISettings, IDisposable
{
public void Dispose() { }
}
public class RegistrySettings : ISettings
{
}
这样,我不允许任何不实现 IDisposable 的 ISettings 实现。例如,我无法控制 ISettings,也无法让其他类实现 ISettingsDisposable 类。
Disposable 显然是一个例子,但您可以在其中放置任何东西 - 我可能想要限制比 ISettings 更严格的想法。
编辑 2:
针对关于结构不具备 == 能力的观点:
public struct StructSettings : ISettings
{
}
我可以执行上述操作并实现一个通用的 StructSettings 版本的 SystemManager:
然后,在 SystemManager 中,我可以比较这两个结构而不会出现运行时错误。
SystemManager<StructSettings> manager = new SystemManager<StructSettings>();
这可行,并且 SystemManager 的构造函数中结构上的 == 不会引发任何运行时错误。
【问题讨论】:
-
我没有答案,但是当您可以直接使用类型 ISettings 时,为什么需要使用泛型?
-
@Manu - 我更新了我的问题,回答了您的问题