Ody*_*dys 10 c# generics inheritance
我正在尝试创建一个类似工厂模式的通用机制.
工厂将是:
public class APlugin<ActionType> where ActionType : IAction
{
// create a new action. Note: ActionType should contain
// an empty constructor
public ActionType CreateAction()
{
return Activator.CreateInstance<ActionType>();
}
}
Run Code Online (Sandbox Code Playgroud)
IAction的后代可能隐藏无参数构造函数,这将导致工厂失败.
Mag*_*tLU 11
通过提供泛型约束,可以确保类具有不带参数的构造函数where T : new()
.但它只会影响类型T
.包含类将不受影响,因此您可以确保ActionType
在您的情况下具有所述构造函数,但您无法在继承的任何类上强制执行它APlugin<T>
.