开发者

What does new() mean?

开发者 https://www.devze.com 2023-01-26 07:35 出处:网络
There is an AuthenticationBase class in WCF RIA Services. The class definition is as follows: // assume using System.ServiceModel.DomainServices.Server.ApplicationServices

There is an AuthenticationBase class in WCF RIA Services. The class definition is as follows:

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

public abstract class AuthenticationBase<T> 
    : Doma开发者_开发问答inService, IAuthentication<T> 
    where T : IUser, new()

What does new() mean in this code?


It's the new constraint.

It specifies that T must not be abstract and must expose a public parameterless constructor in order to be used as a generic type argument for the AuthenticationBase<T> class.


Using the new() keyword requires a default constructor to be defined for said class. Without the keyword, trying to class new() will not compile.

For instance, the following snippet will not compile. The function will try to return a new instance of the parameter.

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

This is a generic type constraint. See this MSDN article.


It means that a type used to fill the generic parameter T must have a public and parameterless constructor. If the type does not implement such a constructor, this will result in a compile-time error.

If the new() generic constraint is applied, as in this example, that allows the class or method (the AuthenticationBase<T> class in this case) to call new T(); to construct a new instance of the specified type. There is no other way, short of reflection (this includes using System.Activator, to construct a new object of a generic type.

0

精彩评论

暂无评论...
验证码 换一张
取 消