c#语言特性6.0

茴香豆的N种写法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
//静态导入(导入单个类的静态方法
using static System.Math;
using static System.String;
namespace Language._6._0
{
    public class Student
    {
        //只读的属性
        public string FirstName { get; }
        //自动属性初始化表达式
        public string LastName { get; set; } = "";

        //Expression-bodied 函数成员
        //字符串内插
        public override string ToString() => $"{FirstName} {LastName}";

        public string FullName => $"{FirstName} {LastName}";

        public Student(Student other)
        {
            //Null 条件运算符
            this.LastName = other?.LastName;
            //等价于 this.LastName = other == null ? null : other.LastName;

            //空合并运算符(??)该运算符左边不为空则返回左边,否则返回右边
            this.LastName = other?.LastName ?? "test";
            Console.WriteLine(this.LastName);
            Console.WriteLine(this.ToString());
            //异常筛选器
            try
            {
                throw new HttpRequestException("aaaa301");
            }
            catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("301"))
            {
                Console.WriteLine("Site Moved");
            }

            //nameof
            Console.WriteLine(nameof(this.FirstName));//FirstName

            //使用索引器初始化关联集合
            Dictionary<int, string> webErrors = new Dictionary<int, string>
            {
                [404] = "Page not Found",
                [302] = "Page moved, but left a forwarding address.",
                [500] = "The web server can't come out to play today."
            };
            Console.WriteLine(webErrors[404]);//Page not Found

            //
            Task.Run(()=>this.ToString());

        }


        


    }
}

 

posted @ 2019-10-03 14:16  Programmer_Life  阅读(218)  评论(0编辑  收藏  举报