C# 7.0 特性实例

本文深入探讨了C# 7.0及后续版本的多项新特性,包括改进的ref和out参数使用、元组的引入、弃元的概念、模式匹配、局部变量和引用返回、局部函数的使用、更多表达式成员、异常表达式以及数字文本化等。通过实例代码,详细解析了这些特性如何提高代码的效率和可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

namespace CSharp_7._0
{
    class Program
    {
        static void Main(string[] args)
        {
            //说第一个特性之前先说下ref和out(会的帅哥请自动略过)
            //ref和out都是按地址传递,使用后都将改变原来参数的数值
            //out的这个特性,一定程度上解决了C#中的函数只能有一个返回值的问题
            //我的理解是:跟指针差不多
            int a = 1;
            int b = 2;
            //1.在7.0之前使用out变量之前要先声明,现在直接在参数传递的时候进行声明就行
            //int c;
            no_function_ref(a,b);
            Console.WriteLine("{0},{1}", a, b);
            function_ref(ref a,ref b);
            Console.WriteLine("{0},{1}",a,b);
            function_out(out int c);
            
            Console.WriteLine(c);
            //2.元组()
            //在4.0中有返回多个值的解决方案
            var data = tuple();
            //var是一个语法糖,在声明变量的时候就已经决定了是什么类型
            //dynamic 并不是在编译的时候确定类型,而是在运行的时候,所以有时候会编译通过,然后运行报错
            Console.WriteLine(data.Item1);
            Console.WriteLine(data.Item2);
            //然而在7.0中提供了一个更好的方案()需要引用system.valueTuple
            var data1 = tuple1();
            Console.WriteLine(data1.a);
            //7.1元组还能这么用
            var pink = ("a","b");
            Console.WriteLine(pink.Item1);
            (string xiao, string shi) aha = ("woshi","xiaoshi");
            Console.WriteLine(aha.xiao);
            //3.0 弃元
            //通常,在进行元组解构或使用 out 参数调用方法时,必须定义一个其值无关紧要且你不打算使用的变量。 
            //为处理此情况,C# 增添了对弃元的支持。 弃元是一个名为 _(下划线字符)的只写变量,可向单个变量赋予要放弃的所有值。
            // 弃元类似于未赋值的变量;不可在代码中使用弃元(赋值语句除外)。
            var (_, _, _, pop1, _, pop2) = QueryCityDataForYears("New York City", 1960, 2010);

            Console.WriteLine($"Population change, 1960 to 2010: {pop2 - pop1:NO}");
            //4.0 模式匹配
            object x = 1;
            if (a is int y) //这里,判断为int后就直接赋值给y
            {
                int d = y + 10;
                Console.WriteLine(d);
            }
            //switch新玩法
            Add("d");
            Console.WriteLine(Add(-1));

            //5.0 局部变量和引用返回
            int x1 = 3;
            ref int x2 = ref x1;  //注意这里,我们通过ref关键字 把x赋给了x1
            x2 = 2;
            Console.WriteLine($"改变后的变量 {nameof(x1)} 值为: {x1}");//$是6.0的特性。相当于string.format()
            //引用返回允许我们可以把值类型当作引用类型来进行return
            int[] arr = { 1, 2, 3, 4, 5 };
            ref int x3 = ref GetByIndex(arr, 2); //调用刚才的方法
            x3 = 99;
            Console.WriteLine($"数组arr[2]的值为: {arr[2]}");
            int y1 = 1, y2 = 2, y3 = 3;
           ref int max_= ref Max(ref y1, ref y2, ref y3);
            Console.WriteLine($"最大值:{max_}");
            
            Max(ref y1, ref y2, ref y3) = 4;
            Console.WriteLine($"最大值:{max_}");
            //6.0 局部函数
            //只在特定的函数中可以访问的函数

            void DoSomeing()
            {
                //调用Dosmeing2
                int data_ = Dosmeing2(100, 200);
                Console.WriteLine(data);
                //定义局部函数,Dosmeing2.
                int Dosmeing2(int a_, int b_)
                {
                    return a_ + b_;
                }
            }
            //7.0 More expression-bodied members
            test test = new test("s");
            //8.0 异常表达式
            //9.0数字文本化
            int bxh = 0xAB_CD_EF;//使数字更加易读

            Console.Read();
        }
        static void function_ref(ref int a,ref int b)//必须是a和b,不能是别的
        {
            a = 2;
            b = 3;
        }
        static void no_function_ref(int a,int b)
        {
            a = 2;
            b = 3;
        }
        static void function_out(out int c)
        {
            c = 5;//控制离开当前方法之前必须给c赋值

        }
        static Tuple<string,string,string> tuple()
        {
            return new Tuple<string, string, string>("a","b","c");
        }
        static (int a,int b,int c) tuple1()
        {
            return (1,2,3);
        }
        private static (string, double, int, int, int, int) QueryCityDataForYears(string name, int year1, int year2)
        {
            int population1 = 0, population2 = 0;
            double area = 0;

            if (name == "New York City")
            {
                area = 468.48;
                if (year1 == 1960)
                {
                    population1 = 7781984;
                }
                if (year2 == 2010)
                {
                    population2 = 8175133;
                }
                return (name, area, year1, population1, year2, population2);
            }

            return ("", 0, 0, 0, 0, 0);
        }
        static dynamic Add(object a)
        {
            dynamic data;
            switch (a)
            {
                case int b when b < 0:
                    data = b + 100;
                    break;
                case int b:
                    data = b++;
                    break;
                case string c:
                    data = c + "aaa";
                    break;
                case List<string> list when list.Count ==5:
                    data = list;
                    break;

                default:
                    data = null;
                    break;
            }
            return data;
        }
        static ref int GetByIndex(int[] arr, int ix) => ref arr[ix];
        static ref int Max(ref int first,ref int second,ref int third)
        {
            ref int Max =ref first > second ? ref first : ref  second;//? :三目运算符
            return ref Max > third ? ref Max : ref third;
        }
        public string IsNull()
        {
            string ax = null;
            return ax ?? throw new Exception("");
        }
        
    }
    class test
    {
        public test(string label) => this.Label = label;
        //public test(string label)
        //{
        //    this.Label = label;
        //}
        // Expression-bodied finalizer
        ~test() => Console.Error.WriteLine("Finalized!");

        private string label;

        // Expression-bodied get / set accessors.
        public string Label
        {
            get => label;
            set => this.label = value ?? "Default label";
        }
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值