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()这段代码意味着什么?
使用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文章.
这意味着用于填充泛型参数的类型T必须具有公共和无参数构造函数.如果类型没有实现这样的构造函数,这将导致编译时错误.
如果new()被施加通用约束,如在这个例子中,其允许类或方法(AuthenticationBase<T>在这种情况下类)来调用new T();构建指定类型的新实例.没有其他的方式,短反射的(这包括使用System.Activator,以构建一个一般类型的新对象.
| 归档时间: |
|
| 查看次数: |
2061 次 |
| 最近记录: |