Skip to main content
 首页 » 编程设计

c#之具有 new() 约束的泛型,不能将字符串作为类型

2024年02月23日26mfrbuaa

我写了一个泛型类

 class MyClass : MyClass<string> { } //this line is in error 
 
 class MyClass<OutputBaseType> : MyClass<OutputBaseType, List<OutputBaseType>> 
     where OutputBaseType : new() //this new constraint is needed 
 {} 
 class MyClass<OutputBaseType,OutputType>  
    where OutputType : ICollection<OutputBaseType>, new() 
    where OutputBaseType : new() 
 { 
     public void Method(OutputBaseType z) 
     { 
         if (z!=null) { ... } 
     } 
 ... 
 } 

因为字符串没有默认构造函数,第一行现在可以工作了。如果我删除此行并修改客户端以显式定义字符串,则出于同样的原因它不起作用。

如果我删除 where OutputBaseType : new()和另一个new()然后它与 OutputBaseType 一起使用的 string但不是 OutputType的 dictionary<...> .这是因为 KeyValuePair<>字典使用的是 struct不是class , 所以不能 null . (我通常不喜欢 null 但这里需要它)

有没有办法让它工作?


修正案:

我删除了对 OutputBaseType 的新约束。 然后用 default(OutputBaseType) 替换 null 的赋值和默认构造的赋值

这看起来很有希望,但我现在在在线条件表达式中有一个错误

OutputBaseType outputItem = ...; 
if (outputItem != default(OutputBaseType)) { _Output.Add(outputItem); } 

错误是:

Operator '!=' cannot be applied to operands of type 'OutputBaseType' and 'OutputBaseType'    

请您参考如下方法:

If I remove where OutputBaseType : new() and the other new() then it works with string OutputBaseType but not with dictionary as OutputType. This is because KeyValuePair<> used by dictionary is a struct not a class, so can not be null. (I don't like null usually but need it here)

您可以简单地使用 default(T)而不是 null对于值类型。值类型的默认构造函数不能由用户定义,并且总是将所有字段初始化为它们的默认值( 0 , null ,...)。所以你不需要 new()如果你只使用 default(T) 约束而不是 new T() ,因为对于值类型,它们是等价的,对于引用类型,您需要 null这恰好是 default任何引用类型。


==在泛型类型上不可用。您可以使用 object.Equals (这会导致装箱)或 EqualityComparer<T>.Default.Equals .我更喜欢第二个:

EqualityComparer<T>.Default.Equals(outputItem, default(OutputBaseType))