我写了一个通用类 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) { ... } } ... }因为string没有默认构造函数,所以第一行现在可以工作。如果我删除此行并修改客户端以显式定义字符串,则由于相同的原因,它将无法正常工作。如果删除where OutputBaseType : new()和另一个new(),则它可以与OutputBaseType的string一起使用,但不能与OutputType的dictionary<...>一起使用。这是因为字典使用的KeyValuePair<>是struct而不是class,因此不能是null。 (我通常不喜欢null,但在这里需要它)有没有办法让它工作?修正案:我删除了对OutputBaseType的新约束。然后将null的分配和默认构造的分配替换为default(OutputBaseType)这看起来很有希望,但是我现在在线上的条件表达式中有一个错误OutputBaseType outputItem = ...;if (outputItem != default(OutputBaseType)) { _Output.Add(outputItem); }错误是:Operator '!=' cannot be applied to operands of type 'OutputBaseType' and 'OutputBaseType' 最佳答案 如果我删除OutputBaseType:new()和另一个new()的地方,则它可以与字符串OutputBaseType一起使用,但不能与字典作为OutputType一起使用。这是因为字典使用的KeyValuePair 是结构而不是类,因此不能为null。 (我通常不喜欢null,但在这里需要它)您可以简单地将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))关于c# - 具有new()约束的泛型,不能将字符串作为类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9128709/
10-10 12:53