What does the new() constraint do on a class definition?

只愿长相守 提交于 2019-12-30 23:27:09

问题


I saw this code example and was wondering what the purpose of the new() constraint was:

public class Client<T> : IClient where T : IClientFactory, new()
{
    public Client(int UserID){ }
}

回答1:


That's called a "'new' constraint". Here's the documentation on it.

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

(Emphasis mine)

Basically, you need it whenever you're creating a new T somewhere in the class, to ensure that you're only able to pass in things which the compiler can create a new instance of.




回答2:


Client is a collection of T objects, and those T objects must implement the IClientFactory interface and have a public parameterless constructor.




回答3:


new() means

The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

Ref Generic Constraints on MSDN



来源:https://stackoverflow.com/questions/13806660/what-does-the-new-constraint-do-on-a-class-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!