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

前端 未结 8 1069
逝去的感伤
逝去的感伤 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:26

    You can also use reflection to fetch the object's constructor and instantiate that way:

    var c = typeof(T).GetConstructor();
    T t = (T)c.Invoke();
    

提交回复
热议问题