How to initialize generic parameter type T?

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

    You have two options:

    You can constrain T: you do this by adding: where T : new() to your method. Now you can only use the someMethod with a type that has a parameterless, default constructor (see Constraints on Type Parameters).

    Or you use default(T). For a reference type, this will give null. But for example, for an integer value this will give 0 (see default Keyword in Generic Code).

    Here is a basic console application that demonstrates the difference:

    using System;
    
    namespace Stackoverflow
    {
        class Program
        {
            public static T SomeNewMethod()
                where T : new()
            {
                return new T();
            }
    
            public static T SomeDefaultMethod()
                where T : new()
            {
                return default(T);
            }
    
            struct MyStruct { }
    
            class MyClass { }
    
            static void Main(string[] args)
            {
                RunWithNew();
                RunWithDefault();
            }
    
            private static void RunWithDefault()
            {
                MyStruct s = SomeDefaultMethod();
                MyClass c = SomeDefaultMethod();
                int i = SomeDefaultMethod();
                bool b = SomeDefaultMethod();
    
                Console.WriteLine("Default");
                Output(s, c, i, b);
            }
    
            private static void RunWithNew()
            {
                MyStruct s = SomeNewMethod();
                MyClass c = SomeNewMethod();
                int i = SomeNewMethod();
                bool b = SomeNewMethod();
    
                Console.WriteLine("New");
                Output(s, c, i, b);
            }
    
            private static void Output(MyStruct s, MyClass c, int i, bool b)
            {
                Console.WriteLine("s: " + s);
                Console.WriteLine("c: " + c);
                Console.WriteLine("i: " + i);
                Console.WriteLine("b: " + b);
            }
    
        }
    }
    

    It produces the following output:

    New
    s: Stackoverflow.Program+MyStruct
    c: Stackoverflow.Program+MyClass
    i: 0
    b: False
    Default
    s: Stackoverflow.Program+MyStruct
    c:
    i: 0
    b: False
    

提交回复
热议问题