Visual Studio 2022 C#9常用新语法Demo

    class Program
    {
        public static bool isFunc(int number) => number > 6;
        static void Main(string[] args)
        {

            //Func<int, int, int> func1 = delegate (int a, int b) { return 0; };
            //Console.WriteLine(func1);
            int number1 = 1;
            string name1 = "00000";

            Func<int, bool> func1 = (number1) => isFunc(number1);
            Console.WriteLine(Convert.ToString(func1));
            Console.ReadKey();

            Func<int, string,Student> func2 = (number1,name1) => 
            {
                return new Student(number1,name1,0);
            };
            

            Func<int,string,string> func3 =delegate (int number1,string _) { return ""; };
          
            
         

            #region  对象声明
            Student student1 = new();
            Student student2 = new() {ID=18,Name= "",Age= 0};
            #endregion
            #region using static

            //using static CoreTest.ReCordInit;

            #endregion

            #region
            Student.Show();
            Show();//通过using static引用可直接访问其它类的方法
            ShowTest("18");
            Console.WriteLine(ShowTest(18));
            #endregion



            #region null验证
            //旧版本null验证
            Student student = null;
            if (student != null)
            {
                string xx = student.Name;
            }
            else{}
            //.net6 版本
            string name = student?.Name;//如果student对象为空就返回null,不为空则返回后面的属性值
            //假如student不为空age为空,可给它赋个默认值用??如同三云运算符?值1 :值2
            int? age = student?.Age ?? 18;
            #endregion


            #region 字符串内插
            //老版本
            StringBuilder builder = new StringBuilder(); builder.Append("");
            string format = string.Format("");
            //.net6
            string texts = $"{builder}-{format}";
            #endregion



            #region 异常过滤    
            try
            {
            }
            catch (Exception ex) when (ex.Message.Contains("ssssTest"))//异常过滤筛选,如异常消息里包含"ssssTest"才进行抛出
            {
                throw;
            }
            #endregion



            #region nameof
            string nameofText = nameof(Student);
            Console.WriteLine($"nameof:{nameofText}");
            #endregion




            #region Dictionary
            //传统版本
            Dictionary<string, int> keyValues = new Dictionary<string, int>();
            keyValues.Add("", 18);
            keyValues.Remove("");
            //.net 6
            Dictionary<string, int> error = new Dictionary<string, int>() {
                {"",18}
            };
            #endregion




            #region ref-out
            //老版本
            int number2;//需要再方法外定义
            outShow("", out number2);
            Console.WriteLine($"out:{number2}");

            int numberText = 18;
            refShow("", ref numberText);//ref 传递得赋初始值
            Console.WriteLine($"ref:{numberText}");

            //.net6 
            outShow("", out int number);
            Console.WriteLine($"out:{number}");

            //实例化时传值到OutRefTestTow类的构造函数中
            OutRefTestTow outRef = new OutRefTestTow(18);
            #endregion





            #region 元组-弃元
            //元组
            (string name, int age) Info = ("张三", 18);
            Console.WriteLine($"元组:名字{Info.name},年龄{Info.age}");
            var Infos = (name: "张三", age: 18);
            Console.WriteLine($"元组s:名字{Infos.name},年龄{Infos.age}");

            (string names,int ages)=YuanZuTest();
            Console.WriteLine($"元组s:名字{names},年龄{ages}");
            //弃元
            var (namess,_,address,_)=QiYuanTest();//QiYuanTest返回四个参数值,但只接收两个,用下划线表示弃元(不接收)
            #endregion





            #region 模式
            IEnumerable<object> ie = new List<object>() {
                0,
                new List<int>(){1,2,3,4,6 },
                100,
                null
            };
            int moshiNumber=MoShi(ie);
            Console.WriteLine($"模式:{ moshiNumber} ");
            #endregion





            #region 本地方法
            Console.WriteLine("本地方法:"+BenDiTest("张三"));
            #endregion




            #region 默认文本表达式
            Func<int,string> func = default(Func<int, string>);
            string TextName = default;
            int TextAge = default;
            Console.WriteLine($"默认文本表达式:{TextAge}-{TextName}-{func}");
            #endregion


            #region 命名实参
            //指定参数名进行赋值,不需要按照顺序
            MingMingShiCan(age:18,name:"张三",address:"中国");
            #endregion

            #region 泛型类-约束类型
            EnumTestTow<EnumClass> enumTest = new EnumTestTow<EnumClass>();
            enumTest.Show(EnumClass.男);
            #endregion

            #region Switch方法
            switchTest(EnumClass.男);
            #endregion

            #region 异步流
            AsyncTest();
            #endregion


            #region 为空判断

            ReCordInit reCord = new ReCordInit(123, "");
            //老版本
            if (string.IsNullOrWhiteSpace(reCord.Name))
            {

            }
            //新版
            if (reCord.Name is not null)
            {

            }
            #endregion

            Console.ReadKey();
        }
        /// <summary>
        /// 异步流方法1
        /// </summary>
        public static async void AsyncTest()
        {
            IAsyncEnumerable<object> asyncEnumerable = AsyncTest2();
            await foreach (var item in asyncEnumerable)
            {
                Console.WriteLine(item);
            }
        }
        /// <summary>
        /// 异步流方法二
        /// </summary>
        /// <returns></returns>
        public static async IAsyncEnumerable<object> AsyncTest2()
        {
            for (int i = 0; i < 6; i++)
            {
                //Task.Delay(1000).ContinueWith(a =>{ 等待1秒钟执行这里面的内容 })
                await Task.Delay(1000).ContinueWith(a =>
                {
                    Console.WriteLine($"线程流:线程ID-{Thread.CurrentThread.ManagedThreadId.ToString("000")}");
                });
                //yield类似于continue;//continue是中止本次执行继续循环,而yield是返回消息出去,继续循环
                yield return i;
            }
        }
        /// <summary>
        /// 元组返回方法
        /// </summary>
        /// <returns></returns>
        public static (string name, int age) YuanZuTest() {
            return ("", 18);
        }
        /// <summary>
        /// 弃元返回方法
        /// </summary>
        /// <returns></returns>
        public static (string name, int age,string address,int sex) QiYuanTest()
        {
            return ("张三", 18,"中国",2);
        }
        /// <summary>
        /// 模式返回方法
        /// </summary>
        /// <returns></returns>
        public static int MoShi(IEnumerable<object> vs)
        {
            int sum = 0;
            foreach (var item in vs)
            {
                switch (item)
                {
                    case 0:
                        break;
                    case IEnumerable<int> numberList://类型为IEnumerable<int>即可往下执行
                        {
                            foreach (int items in numberList)
                            {
                                sum += (items > 0) ? items : 0;
                            }
                            break;
                        }
                    case int a when a > 0://类型为int且数值大于0的即可往下执行
                        sum += a;
                        break;
                    case null://值为null即可往下执行
                        break; 
                    default:
                        break;
                }
            }
            return sum;
        }
        /// <summary>
        /// 本地方法
        /// </summary>
        /// <returns></returns>
        public static string BenDiTest(string name)
        {
            return BenDiTest2(name);

            static string BenDiTest2(string name) {
                return name + "123";
            }
        }
        /// <summary>
        /// 命名实参方法
        /// </summary>
        public static void MingMingShiCan(string name, string address, int age) {
            Console.WriteLine($"命名实参:{name}-{address}-{age}");
        }
       
    }

    class OutRefTest{
        public static void outShow(string Text,out int number) {
            number =+ 1;
        }
        public static void refShow(string Text, ref int numberText)
        {
            numberText += 1;
        }
    }
    class OutRefTestOne
    {
        public OutRefTestOne(int a,out string b) {
            b = "Text";
            string text = b + a.ToString();
            b = text;
        }
      
    }
    class OutRefTestTow: OutRefTestOne
    {
        public OutRefTestTow(int a):base(a,out string b)
        {
            Console.WriteLine($"OutRefTestTow:{b}");
        }
    }
    /// <summary>
    /// 泛型类-约束类型
    /// </summary>
    /// <typeparam name="T"></typeparam>
    class EnumTestTow<T> where T:Enum
    {
        public void Show(T t) {
            Console.WriteLine($"泛型类-约束:{nameof(T)}");
        }
    }
    /// <summary>
    /// 枚举类
    /// </summary>
    enum EnumClass { 
        男=0,女=1    
    }
    /// <summary>
    /// 接口类
    /// </summary>
    interface JieKouLei {

        /// <summary>
        /// 老版本接口类里面的方法不能有方法体,只能去实现类实现方法
        /// </summary>
        public void Show();
        /// <summary>
        /// .net 6 接口类可以存在方法体
        /// </summary>
        public void ShowInfo() {
            Console.WriteLine("Hello接口类!");
        }
    }
    /// <summary>
    /// reCord只读类
    /// </summary>
    record ReCordInit
    {
        public ReCordInit(int id, string name) => (ID, Name) = (id, name);
        /// <summary>
        /// init只读
        /// </summary>
        public int ID { get; init; }
        public string Name { get; init; }

        //老方法
        //public string MyProperty { get; }
    }
public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int? Age { get; set; }

        #region 原始方法写法和.net方法写法
        public Student(int id, string name, int? age) => (ID, Name, Age) = (id,name,age);
        public Student() { }
        /// <summary>
        /// 之前方法写法
        /// </summary>
        /// <param name="age"></param>
        public static void Show(object age) {
            Console.WriteLine($"Hello Student!{age}");
        }
        public static void Show()
        {
            Console.WriteLine($"Hello Student!");
        }
        /// <summary>
        /// .Net5写法
        /// </summary>
        /// <param name="age"></param>
        public static void ShowTest(string age) => Show(age);
        public static string ShowTest(int age) => $"年龄:{age}";

        #endregion

        /// <summary>
        /// .Net5 一个字段可以直接将其它字段拼接起来
        /// </summary>
        public string Text => $"{ID}-{Name}-{Age}";

    }
 class SwitchMethods
    {
        /// <summary>
        /// switch模式方法
        /// </summary>
        public static string switchTest(EnumClass enumClass) => enumClass switch
        {
            //如enumClass为:EnumClass.男则返回男,为EnumClass.女则返回女,都不等于则抛出异常
            EnumClass.男 => "男",
            EnumClass.女 => "女",
            _ => throw new NotImplementedException("枚举不存在")

        };
        /// <summary>
        /// switch属性模式
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static int SwitchTest(Info info) => info switch
        {
            //如Text1属性为张三则返回0,Text2属性为18则返回1
            { Text1:"张三"}=>0,
            { Text2:18}=>1,
            _=>throw new NotImplementedException("无")
        };
        /// <summary>
        /// switch元组模式
        /// </summary>
        /// <param name="Text1"></param>
        /// <param name="Text2"></param>
        /// <returns></returns>
        public static string SwitchTest(string Text1, int Text2) => (Text1, Text2) switch
        {
            //如Text1属性为张三且Text2为18则返回0,如Text1属性为李四且Text2为20则返回1
            ("张三",18)=>"0",
            ("李四",20)=>"1", 
            _=>throw new NotImplementedException("无")

        };
        /// <summary>
        /// 位置模式
        /// </summary>
        public static void SwitchShow() { 

            Info info = new Info("张三",18);

            string name;
            int age;

            info.Methods(out name,out age);
            Console.WriteLine($"位置模式:{name}-{age}");
        }
}
    class Info {
        public  string Text1 { get; set; }
        public  int Text2 { get; set; }

        public Info(string text1, int text2) =>(Text1, Text2)= (text1, text2);

        /// <summary>
        /// 位置模式
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        public  void Methods(out string a, out int b) => (a, b) = (Text1, Text2);
    }

第一个代码段全部放Program类中,第二个代码段新建一个ReCordInit只读类,

第三个代码段新建一个Student类,第四个代码段新建一个SwitchMethods类。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值