new()是什么意思?

syn*_*tic 13 c# generics new-operator

AuthenticationBaseWCF RIA服务中有一个类.类定义如下:

// assume using System.ServiceModel.DomainServices.Server.ApplicationServices

public abstract class AuthenticationBase<T> 
    : DomainService, IAuthentication<T> 
    where T : IUser, new()
Run Code Online (Sandbox Code Playgroud)

new()这段代码意味着什么?

Fré*_*idi 21

这是新的约束.

它指定了T不能是抽象的和必须公开公共的无参数的构造函数,以用作泛型类型参数AuthenticationBase<T>类.

  • Teeny weeny更正:类型必须具有这些功能才能用作泛型类型*参数*.`T`是泛型类型*参数*,但实际使用的类型(例如`object`,`int`)是类型参数. (2认同)

AK.*_*AK. 7

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

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

public T Foo <T> ()
// Compile error without the next line
// where T: new()
{
    T newInstance = new T();
    return newInstance;
}
Run Code Online (Sandbox Code Playgroud)

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


cdh*_*wie 5

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

如果new()被施加通用约束,如在这个例子中,其允许类或方法(AuthenticationBase<T>在这种情况下类)来调用new T();构建指定类型的新实例.没有其他的方式,短反射的(这包括使用System.Activator,以构建一个一般类型的新对象.