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

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

    Declare your method like this:

    public string InstantiateType(string firstName, string lastName) 
                  where T : IPerson, new()
    

    Notice the additional constraint at the end. Then create a new instance in the method body:

    T obj = new T();    
    

提交回复
热议问题