What does the new() constraint do on a class defin

2019-02-23 21: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){ }
}

3条回答
贪生不怕死
2楼-- · 2019-02-23 21:28

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-23 21:41

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

查看更多
Explosion°爆炸
4楼-- · 2019-02-23 21:43

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.

查看更多
登录 后发表回答