If one wants to create a new instance of a generic, the new constraint needs to be defined, like so:
public T SomeMethod<T>() where T : new()
{
return new T();
}
Is it possible, using reflection, to create an instance of T without the new constraint, like so (contains pseudocode):
public T SomeMethod<T>()
{
if (T has a default constructor)
{
return a new instance of T;
}
else
{
return Factory<T>.CreateNew();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…