带有可选参数的构造函数违反new()约束

我有一个这个构造函数的类:

public Currency(Guid? vcurrencyUI = null) : base(vcurrencyUI) { } 

我想使用new()约束这个类,但我收到此错误:

‘Currency’必须是具有公共无参数构造函数的非抽象类型,才能在generics类型或方法中将其用作参数’T’…

如果我拆分构造函数一切正常:

 public Currency(Guid? vcurrencyUI) : base(vcurrencyUI) { } public Currency() : base() { } 

为什么我需要拆分构造函数?

因为具有默认参数的构造函数不是无参数构造函数。

编译器在编译时“填充”默认参数。 当你写:

 var foo = new Currency(); 

编译器生成:

 var foo = new Currency(null); 

编译类时,编译器会创建一个带有Guid?的构造函数Guid? 参数,并且还生成一些有效的元数据“如果在编译时未提供参数,则提供null 。 但是没有为该类型生成无参数构造函数。

new()约束要求为该类型定义无参数构造函数,并且它不接受具有单个默认参数的构造函数。 很可能是因为最终必须调用构造函数的运行时不理解默认参数的概念。

虽然Jim 已经回答了你的问题,但请注意,更通用的方法可能是允许传递一个委托来实例化你的具体类,而不是强制所有的实现都是无参数的。

即代替这个:

 public class Something where T : new() { public T CreateInstance() { return new T(); } } 

您可以传递一个显式委托,它将执行任何自定义实例化逻辑:

 // note that the constraint is now removed public class Something { private readonly Func _ctor; public Something(Func ctor) { _ctor = ctor; } public T CreateInstance() { return _ctor(); } } // and you can now pass arbitrary constructor logic as a delegate var x = new Something( () => new Currency(null) ); 

这也允许您创建一个帮助程序类,并提供两个选项:

 public class Something { // this allows you to use a parameterless ctor public static Something Create() where T : new() { return new Something(() => new T()); } // this allows you to specify a custom one public static Something Create(Func ctor) { return new Something(ctor); } }