什么是新的()做`其中T:新的()` [英] What does new() do in `where T: new()?`

查看:189
本文介绍了什么是新的()做`其中T:新的()`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么新的()做下面的code?

 公共类A< T>其中T:B,新的()
 

解决方案

这是对你的类的泛型参数的约束,即传递的泛型类型的任何类型必须有一个无参数的构造函数。

因此​​,

 公共类C:将B
{
    市民C(){}
}
 

将是一个有效的类型。你可以创建一个新的实例 A< C>

不过,

 大众D级:乙
{
   公共D(INT东西){}
}
 

也不会满足的约束,你就不会被允许创建 A&LT的新实例; D> 。如果您还增加了一个参数的构造函数为D,那么这将再次成为有效的。

What does the new() do in the code below?

public class A<T> where T : B, new()

解决方案

This is a constraint on the generic parameter of your class, meaning that any type that is passed as the generic type must have a parameterless constructor.

So,

public class C : B
{
    public C() {}
}

would be a valid type. You could create a new instance of A<C>.

However,

public class D : B
{
   public D(int something) {}
}

would not satisfy the constraint, and you would not be allowed to create a new instance of A<D>. If you also added a parameterless constructor to D, then it would again be valid.

这篇关于什么是新的()做`其中T:新的()`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆