If BaseFruit
has a constructor that accepts an int weight
, can I instantiate a piece of fruit in a generic method like this?
public void AddFruit<T>()where T: BaseFruit{
BaseFruit fruit = new T(weight); /*new Apple(150);*/
fruit.Enlist(fruitManager);
}
An example is added behind comments. It seems I can only do this if I give BaseFruit
a parameterless constructor and then fill in everything through member variables. In my real code (not about fruit) this is rather impractical.
-Update-
So it seems it can't be solved by constraints in any way then. From the answers there are three candidate solutions:
- Factory Pattern
- Reflection
- Activator
I tend to think reflection is the least clean one, but I can't decide between the other two.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…