What does new() mean?

后端 未结 3 768

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

// assume using System.ServiceModel.DomainServices         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 21:54

    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  ()
    // 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.

提交回复
热议问题