.net 4.6之后的新特性

本文介绍了C#中自动属性的最新初始化方法,展示了如何通过新语法快速设置默认值;讲解了String.Format的简化使用,以及表达式属性和方法的实践。同时涵盖了泛型集合和静态类引用的改进,以及新技术如nameof和null条件表达式的应用。
摘要由CSDN通过智能技术生成

01.自动属性新初始化方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewDemo
{
    //以前用法:自动属性不能在声明的时候初始化
    //class Student
    //{
    //    public Student()
    //    {
    //        StudentId = 1001;
    //        Name = "张欣欣";
    //        Age = 25;
    //    }
    //    public int StudentId { get; set; }
    //    public string Name { get; set; }
    //    public int Age { get; set; }
    //    public string Gender
    //    {
    //        get { return Gender; }
    //    }
    //}

    //新用法:声明的同时可以初始化,并且允许只读属性初始化
    class Student
    {
        public int StudentId { get; set; } = 1001;
        public string Name { get; set; } = "张欣欣";
        public int Age { get; set; } = 25;
        public string Gender { get; } = "男";
    }

}

02.String.Format的简化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewDemo
{
    class NewFormat
    {
        //旧用法:string.Format("{0},{1}",变量1,变量2)实现格式化输出
        public void OldMethod()
        {
            Student objStudent = new NewDemo.Student();

            string s1 = string.Format("{0},{1}", objStudent.Name, objStudent.Age);

            string s2 = string.Format("姓名={0},年龄={1}", objStudent.Name, objStudent.Age);
            Console.WriteLine("{0},\r\n{1}", s1, s2);
            Console.WriteLine();

            string s3 = string.Format("{0,10},{1:d3}", objStudent.Name, objStudent.Age);
            string s4 = string.Format("{0,10},{1,10:d3}", objStudent.Name, objStudent.Age);
            Console.WriteLine("{0},\r\n{1}", s3, s4);
            Console.WriteLine();

            string s5 = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
            Console.WriteLine(s5);
            Console.WriteLine();

            string sql = "select Name from Students where StudentId={0} and Age>{1}";
            Console.WriteLine(sql, objStudent.StudentId, objStudent.Age);

        }
        //新用法:在字符串前面添加“$”前缀,(变量可以直接写到{}内,并且有很强的智能提示)
        public void NewMethod()
        {
            Student objStudent = new NewDemo.Student();
            string s1 = $"{objStudent.Name },{objStudent.Age }";
            string s2 = $"姓名={objStudent.Name },年龄={objStudent.Age }";
            Console.WriteLine($"{ s1} ,\r\n{ s2} ");

            string s3 = $"{objStudent.Name,10},{objStudent.Age:d3}";
            string s4 = $"{objStudent.Name,10},{objStudent.Age,10:d3}";
            Console.WriteLine($"{ s3} ,\r\n{ s4} ");

            string s5 = $"{DateTime.Now:yyyy-MM-dd}";
            Console.WriteLine(s5);

            //典型应用
            string sql = $"select Name from Students where StudentId={objStudent.StudentId} and Age>{objStudent.Age }";
            Console.WriteLine( sql);
        }
    }
}

03.表达式属性和表达式方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewDemo
{
    /// <summary>
    /// 表达式应用的新特性
    /// </summary>
    class ExpressionApp
    {

        //【1】表达式属性:只有一个get访问器的单行属性可以使用lambda语法编写

        public DateTime Birthday { get; set; } = Convert.ToDateTime("1990-1-10");

        //public int Age
        //{
        //    get { return DateTime.Now.Year - Birthday.Year; }
        //}
        public int Age => DateTime.Now.Year - Birthday.Year;

        //【2】表达式方法:只有一条语句的方法可以使用lambda语法编写
        //public int Add(int a, int b)
        //{
        //    return a + b;
        //}

        public int Add(int a, int b) => a + b;
    }
}

04.泛型集合Dictionary初始化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewDemo
{
    /// <summary>
    /// 泛型集合的新初始化方法
    /// </summary>
    class NewCollectionInit
    {
        public Dictionary<string, int> OldMethod()
        {
            Dictionary<string, int> student = new Dictionary<string, int>();
            student.Add("张三", 25);
            student.Add("李四", 34);
            student.Add("王五", 26);
            return student;
        }
        //新的初始化方法
        public Dictionary<string, int> NewMethod()
        {
            Dictionary<string, int> student = new Dictionary<string, int>()
            {
                ["张三"] = 25,
                ["李四"] = 34,
                ["王五"] = 26
            };
            return student;
        }
    }
}

05.static声明静态类的引用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using static System.Math;


namespace NewDemo
{
    /// <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 NewMethod1(int a, int b)
        {
            return Abs(a) + Abs(b);
        }
        public static int NewMethod2(int a, int b) => Abs(a) + Abs(b);
    }
}

06.nameof表达式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewDemo
{
    /// <summary>
    /// nameof表达式
    /// </summary>
    class NameofExpressions
    {

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

            }
        }
        //新用法:使用nameof,当参数变化时会在引用的地方同步变化,避免程序的硬编码
        //nameof里面可以是:类名、方法名、参数名、属性名
        public void NewMethod(int account)
        {
            if (account < 100)
            {
                throw new ArgumentException($"参数{nameof(account)}的值不能小于100!");
            }
            else
            {
                //其他操作...

            }
        }

    }
}

07.Null条件表达式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewDemo
{
    /// <summary>
    /// null操作符:null传递操作符简化了空值的检查
    /// </summary>
    class NullOperator
    {
        string[] sArray = new string[] { "bc", "cde", null, "efgg", null };

        //以前用法
        public void OldMethod()
        {
            foreach (string item in sArray)
            {
                var length = item == null ? 0 : item.Length;
                Console.WriteLine(length);
            }
            Console.WriteLine("---");
        }
        //新方法:
        public void NewMethod()
        {
            foreach (string item in sArray)
            {
                var length = item?.Length;//如果为null直接输出null
                Console.WriteLine(length);
            }
            Console.WriteLine("---");
            foreach (string item in sArray)
            {
                var length = item?.Length ?? 0;
                Console.WriteLine(length);
            }
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值