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

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

    Couple of ways.

    Without specifying the type must have a constructor:

    T obj = default(T); //which will produce null for reference types
    

    With a constructor:

    T obj = new T();
    

    But this requires the clause:

    where T : new()
    

提交回复
热议问题