In C#, how to instantiate a passed generic type inside a method?

前端 未结 8 1066
逝去的感伤
逝去的感伤 2020-11-30 21:19

How can I instantiate the type T inside my InstantiateType method below?

I\'m getting the error: \'T\' is a \'type parameter\' but is u

8条回答
  •  一向
    一向 (楼主)
    2020-11-30 21:25

    To extend on the answers above, adding where T:new() constraint to a generic method will require T to have a public, parameterless constructor.

    If you want to avoid that - and in a factory pattern you sometimes force the others to go through your factory method and not directly through the constructor - then the alternative is to use reflection (Activator.CreateInstance...) and keep the default constructor private. But this comes with a performance penalty, of course.

提交回复
热议问题