类型参数必须有一个公共(public)的无参数构造函数。与其他约束一起使用时,必须最后指定 new() 约束。
当需要这个约束时,你们能给我一个示例场景吗?
最佳答案
这本质上就是 new()
约束归结为:
class Factory<T> where T : new()
{
public T Create()
{
return new T();
// ^^^^^^^
// this requires the new() type constraint.
}
}
现在,您不能将参数传递给构造函数。如果你仍然想初始化新对象,你可以实现这个,例如通过引入进一步的约束:
interface ILikeBananas
{
double GreenBananaPreferenceFactor { get; set; }
}
class Factory<T> where T : ILikeBananas, new()
{
public T Create(double greenBananaPreferenceFactor)
{
ILikeBananas result = new T();
result.GreenBananaPreferenceFactor = greenBananaPreferenceFactor;
return (T)result;
// ^^^^^^^^^
// freely converting between ILikeBananas and T is permitted
// only because of the interface constraint.
}
}
请注意,另一种实例化对象的方法是通过 Activator.CreateInstance
,这为您提供了更多自由,例如将参数直接传递给构造函数。
Activator.CreateInstance
并不严格要求 new()
约束;但是,被实例化的类型仍然需要提供合适的构造函数。
关于c# - 泛型:何时使用 new() 作为类型参数的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3691734/