我想提供某種類型的通用約束限制類的工廠,不過,我需要確保該產品創建具有一定的構造,以使我廠工作。通用工廠 - 預計某些構造
public interface IFactory<TProduct>
where TProduct: class, IMyRestriction
{
TProduct Create();
}
類,它實現IMyRestriction:
public class MyRestriction : IMyRestriction {
public MyRestriction(IArgumentType1 arg1, IArgumentType2 arg2) {
...
}
}
這將使這項工作...
public class MyFactory<TProduct> : IFactory<TProduct>
where TProduct: class, IMyRestriction
{
public TProduct Create() {
// args provided by factory constructor
Activator.CreateInstance(typeof(TProduct), arg1, arg2);
}
}
...但沒有像這樣的類:
public class MyDerivedRestriction : MyRestriction {
public MyDerivedRestriction()
: base(null, null)
{
}
}
我能夠限制的唯一方法在使用泛型的某個構造函數中使用new()約束,但在這種情況下沒有意義。
您確定不應該使用IoC容器,例如['Autofac'](http://autofac.org/)或['StructureMap'](http:// docs .structuremap.net /)? – 2014-10-07 08:15:05