How to initialize generic parameter type T?

前端 未结 5 1963
甜味超标
甜味超标 2021-02-05 04:19

Simple question:
If you have a string x, to initialize it you simple do one of the following:

string x = String.Empty;  

or

5条回答
  •  我在风中等你
    2021-02-05 05:08

    You need to add a new constraint for the type parameter T.

    void someMethod(T y) where T : new()
    {
        T x = new T();  
        ...
    }
    

    This will only be valid for types with a default constructor however.

    The where clause for T is a generic type constraint. In this case, it requires that any type T this method is applied to must have a public parameterless constructor.

提交回复
热议问题