new()是什么意思?

WCF RIA Services中有一个AuthenticationBase类。 类定义如下:

 // assume using System.ServiceModel.DomainServices.Server.ApplicationServices public abstract class AuthenticationBase : DomainService, IAuthentication where T : IUser, new() 

new()在此代码中的含义是什么?

这是新的约束 。

它指定T不能是抽象的,并且必须公开一个公共无参数构造函数 ,以便用作AuthenticationBase类的generics类型参数 。

使用new()关键字需要为所述类定义默认构造函数。 没有关键字,尝试类new()将无法编译。

例如,以下代码段将无法编译。 该函数将尝试返回参数的新实例。

 public T Foo  () // Compile error without the next line // where T: new() { T newInstance = new T(); return newInstance; } 

这是一种通用类型约束。 请参阅此MSDN文章 。

这意味着用于填充generics参数T必须具有公共和无参数构造函数。 如果类型没有实现这样的构造函数,这将导致编译时错误。

如果应用new()generics约束(如本示例所示),则允许类或方法(在本例中为AuthenticationBase类)调用new T(); 构造指定类型的新实例。 没有其他方法,缺少reflection(这包括使用System.Activator ,来构造generics类型的新对象)。