C#default关键字(泛型代码中的默认关键字)

在泛型类和泛型方法中产生的一个问题是,在预先未知以下情况时,如何将默认值分配给参数化类型 T:
T 是引用类型还是值类型。
如果 T 为值类型,则它是数值还是结构。
给定参数化类型 T 的一个变量 t,只有当 T 为引用类型时,语句 t = null 才有效;只有当 T 为数值类型而不是结构时,语句 t = 0 才能正常使用。
解决方案是使用 default 关键字,此关键字对于引用类型会返回 null,对于数值类型会返回零。
对于结构,此关键字将返回初始化为零或 null 的每个结构成员,具体取决于这些结构是值类型还是引用类型。
对于可以为 null 的值类型,默认返回 System.Nullable,它像任何结构一样初始化。

    class Program
    {
        static void Main(string[] args)
        {
            int a = Get(10);//0
            string b = Get("aaa");//null
            test test = Get(new test() { name = "wolf", age = 10 });//null
            test1 test1 = Get(new test1() { name = "wolf", age = 10 });//age = 0 name = null
            Console.ReadLine();
        }

        static T Get(T key)
        {
            return default(T);
        }

    }

    public class test
    {
        public string name { get; set; }
        public int age { get; set; }
    }

    public struct test1
    {
        public string name { get; set; }
        public int age { get; set; }
    }

 

转载于:https://www.cnblogs.com/lgxlsm/p/7280596.html

你可能感兴趣的:(C#default关键字(泛型代码中的默认关键字))