c#6.0新特性(2)

泛型集合的新初始化方法:

/// <summary>
    /// 泛型集合的新初始化方法
    /// </summary>
    class NewCollectionInit
    {
        public Dictionary<string, int> OldMethod()
        {
            Dictionary<string, int> student = new Dictionary<string, int>();
            student.Add("张宇", 24);
            student.Add("王宇", 29);
            student.Add("李宇", 21);
            student.Add("周宇", 28);
            return student;
        }
        //新的初始化方法
        public Dictionary <string,int> NewMethod()
        {
            Dictionary<string, int> student = new Dictionary<string, int>()
            {
                ["张宇"] = 24,
                ["王宇"] = 29,
                ["李宇"] = 21,
                ["周宇"] = 28,
            };
            return student;
        }
        
    }
 NewCollectionInit objNew = new NewCollectionInit();
            Dictionary<string, int> student = objNew.NewMethod();
            foreach (string item in student.Keys)
            {
                Console.WriteLine(item + student[item]);
            }
 /// <summary>
    /// static 声明静态类的引用
    /// </summary>
    class StaticClassApp
    {
        //以前用法:两个数的绝对值相加
        public static int OldMethod(int a,int b)
        {
            return Math.Abs(a) + Math.Abs(b);
        }
        //现在用法:使用using static System.Math;提前引入静态类,避免每次都调用Math
        public static int NewMethod(int a,int b)
        {
            return Abs(a) + Abs(b);
        }
        public static int NewMethod1(int a, int b) => Abs(a) + Abs(b);
    }

新用法:使用nameof,当参数变化时会在引用的地方同步变化,避免程序的硬编码

/// <summary>
    /// nameof表达式
    /// </summary>
    class NameofExpressions
    {
        //以前用法:当参数名称变化的时候,被引用地方需要同步修改
        public void OldMethod(int account1)
        {
            if (account1 < 100)
            {
                throw new ArgumentException("参数account1的值不能小于100");
            }
            else
            {
                //其他操作
            }
        }
        public void NewMethod(int account)
        {
            if(account < 100)
            {
                throw new ArgumentException($"参数{nameof(account)}的值不能小于100");
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_37589387/article/details/88570874