zoukankan      html  css  js  c++  java
  • C# 6.0部分新特性

    Struct的默认构造函数和属性赋值


    我看C# 6 introduce 提到这个功能。但vs2015搭载的NET4.6貌似还不支持这个。所以也不好判断。


    属性赋值


        /// <summary>
        /// 属性赋值
        /// 只读属性表达式
        /// </summary>
        public class UserInfo1
        {
            public string Name { get; set; } = "Tom";
            public int Age { get; set; } = 12;
    
            public int Height { get { return 168 + new Random().Next(1, 10); } }
            public int HeightNew => 168 + new Random().Next(1, 10);
        }


    方法表达式

      /// <summary>
        /// 方法表达式
        /// </summary>
        public class UserInfo2
        {
            public string Name { get; set; } = "Tom";
            public int Age { get; set; } = 12;
    
            public void Introduce()
            {
                //C#6 字符串拼接方式,很方便吧!
                Console.WriteLine($"my name is {Name},{Age}.");
            }
    
            public void IntroduceNew() => Console.WriteLine($"my name is {Name},{Age}.");
    
        }

     

    空引用检查


        /// <summary>
        ///  空引用检查 
        /// </summary>
        public class UserInfo3
        {
            public string Name { get; set; }  
            public int Age { get; set; } 
    
          
            public   void SayHello(UserInfo3 user)
            {
                if (user.Name==null)
                    return;
                Console.WriteLine($"hi, {user.Name}");
            }
            //输出 hi,  
            public void SayHelloNew(UserInfo3 user)
            {
                Console.WriteLine($"hi, {user?.Name}");
            }
        }

    获取参数/变量的名称


            static void Main(string[] args)
            {
                //UserInfo3 user3=new UserInfo3();
                //user3.SayHello(user3);
                //user3.SayHelloNew(user3);
    
    
                GetObjectName();
    
                Console.ReadLine();
            }
    
    
            /// <summary>
            /// 获取参数/变量的名称
            /// 原先要用反射获取
            /// </summary>
            public static void GetObjectName()
            {
                Console.WriteLine( nameof(UserInfo3));
            }






  • 相关阅读:
    抽象类中可以存在的成员
    读暗时间后感
    使用正则表达式限制QLineEdit不能输入大于某个整数
    QSharedMemory 使用
    BUUCTF-misc九连环 详解
    BUUCTF-数据包中的线索 1
    BUUCTF-Windows系统密码
    [CISCN2019 华北赛区 Day2 Web1]Hack World 1详解
    [ZJCTF 2019]NiZhuanSiWei 1详解
    BUUCTF [BJDCTF2020]Easy MD5 详解
  • 原文地址:https://www.cnblogs.com/yuanhuaming/p/4516398.html
Copyright © 2011-2022 走看看