C# 与接口一起使用的新关键字

C# 与接口一起使用的新关键字,c#,interface,new-operator,C#,Interface,New Operator,虽然我已经看过了关于这个问题的几个答案,但我仍然不确定是否知道这行代码在做什么: public class SomeClass<P> : SomeInterface where P : AnotherInterface, new(){...} 公共类SomeClass:SomeInterface,其中P:AnotherInterface,new(){…} new()在做什么?当您通常看到其中T:Whatever[,Whatever2]引用其他接口和类时,它也可以是以下任一接口和类

虽然我已经看过了关于这个问题的几个答案,但我仍然不确定是否知道这行代码在做什么:

public class SomeClass<P> : SomeInterface where P : AnotherInterface, new(){...}
公共类SomeClass

:SomeInterface,其中P:AnotherInterface,new(){…}


new()
在做什么?

当您通常看到
其中T:Whatever[,Whatever2]
引用其他接口和类时,它也可以是以下任一接口和类之一:

  • 其中T:struct
    -T必须是值类型
  • 其中T:class
    -T必须是引用类型
  • 其中T:unmanaged
    -T及其所有变量必须是值类型,以及这些值类型具有的变量。。。等等
  • 其中T:new()
    -T必须具有无参数构造函数。必须最后指定此约束
  • 其中T:U
    -T必须是或派生自为U提供的参数

new()
P
必须是一个具有无参数构造函数的类型。如果您想知道,这允许您在接口的代码中调用
new T()
(或者在您的示例中是
new P()
),非常好!非常感谢。你提到的那个人真的很好地解释了这一点@是的,我应该用T而不是P。。。