WCF RIA Services中有一个AuthenticationBase
类。类定义如下:
// assume using System.ServiceModel.DomainServices.Server.ApplicationServices
public abstract class AuthenticationBase<T>
: DomainService, IAuthentication<T>
where T : IUser, new()
此代码中new()
的含义是什么?
答案 0 :(得分:21)
它指定T
不得为abstract且必须公开public无参数constructor才能用作generic type argument {{3}} 1}}类。
答案 1 :(得分:7)
使用new()关键字需要为所述类定义默认构造函数。没有关键字,尝试类new()将无法编译。
例如,以下代码段将无法编译。该函数将尝试返回参数的新实例。
public T Foo <T> ()
// Compile error without the next line
// where T: new()
{
T newInstance = new T();
return newInstance;
}
这是一种通用类型约束。请参阅此MSDN article。
答案 2 :(得分:5)
这意味着用于填充泛型参数T
的类型必须具有公共和无参数构造函数。如果类型没有实现这样的构造函数,这将导致编译时错误。
如果应用了new()
泛型约束(如本示例所示),则允许类或方法(在本例中为AuthenticationBase<T>
类)调用new T();
来构造新实例指定类型的。没有其他方法,缺少反射(包括使用System.Activator
)来构造泛型类型的新对象。