How to initialize generic parameter type T?

前端 未结 5 1961
甜味超标
甜味超标 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

    use default keyword.

    T x = default(T);
    

    See: default Keyword in Generic Code (C# Programming Guide)

    Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types.

提交回复
热议问题