关于在c#中使用新约束
我从不使用新的约束,因为我不清楚使用它。 在这里,我发现了一个样本,但我只是不明白使用。 这是代码
class ItemFactory where T : new() { public T GetNewItem() { return new T(); } } public class ItemFactory2 where T : IComparable, new() { }
所以任何人都请让我理解使用新的Constraint与小而简单的样品,以供现实世界使用。 谢谢
除了Darin的答案之外 ,这样的事情会失败,因为Bar
没有无参数构造函数
class ItemFactory where T : new() { public T GetNewItem() { return new T(); } } class Foo : ItemFactory { } class Bar { public Bar(int a) { } }
实际错误是: 'Bar' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'ItemFactory
以下也会失败:
class ItemFactory { public T GetNewItem() { return new T(); } }
实际错误是: Cannot create an instance of the variable type 'T' because it does not have the new() constraint
此约束要求使用的generics类型是非抽象的,并且它具有允许您调用它的默认(无参数)构造函数。
工作范例:
class ItemFactory where T : new() { public T GetNewItem() { return new T(); } }
这显然现在会迫使你为作为generics参数传递的类型有一个无参数构造函数:
var factory1 = new ItemFactory(); // OK var factory2 = new ItemFactory(); // doesn't compile because FileInfo doesn't have a default constructor var factory3 = new ItemFactory(); // doesn't compile because Stream is an abstract class
非工作示例:
class ItemFactory { public T GetNewItem() { return new T(); // error here => you cannot call the constructor because you don't know if T possess such constructor } }
新约束指定generics类声明中的任何类型参数都必须具有公共无参数构造函数。
引自官方网站
在您的示例中,约束作用于类声明中的
。 在第一种情况下,它要求通用T
对象具有默认(无参数)构造函数。 在第二个示例中,它要求T
应该具有默认的无参数构造函数,并且它必须实现IComparable
接口。
您可以读取new()
,就好像它是一个带有构造函数的接口。 就像IComparable指定类型T具有方法CompareTo一样,新约束指定类型T具有公共构造函数。