其他分享
首页 > 其他分享> > C Sharp 语法6 学习笔记

C Sharp 语法6 学习笔记

作者:互联网

Sharp 6 新增的语法特性  https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-6
		
	1.只读自动属性
		1.只读属性只能通过构造函数赋值
		   public Student(string lastname, string firstName)
		   {
			 this.LastName = lastname;
			 this.FirstName = firstName;
		   }
		  public string LastName { get; }
		  public string FirstName { get;  }
		2.只读属性的初始化
			 public ICollection<double> Geades { get; } = new List<double>();
		3.gose to 取值
			  public override string ToString() => $"{FirstName}-{LastName}";
			  public string fullName => $"{FirstName}-{LastName}";
2 using static
             1. 正常情况通过静态类访问静态方法
                using static 引用任意类型,访问静态方法是不需要加类型名称
                
                StaticClass.Next();
                objClass.Nex1t();
                Next();
                Nex1t();
3.null 条件运算
            1.单个运算符 ? 出现在引用类型或可以Null的类型后面追加,必须支持可空 null类型
            Student student = null;
            string name = student?.LastName?.ToString();
            int? id = student?.Id;

            2.两元表达式 ?? 当前值不可空(null)取当前值返回否则获取后面值,
            student = new Student("AB", "CD");
            string fullname = student?.fullName?.ToString();
            int? testid = student?.Id ?? 22;
            student.Id = 33;
            testid = student?.Id ?? 22;
4.字符串内插槽
			string lastname = "aaaa";
            string first = "zhang";
            string fullName = $"{lastname}------{first}"; 
5.异常筛选器,可以根据输出来选择相应的异常处理
		 public static void ExceptionShow()
			{
				try
				{
					throw new Exception("AAA");
				}
				catch (Exception ex) when (ex.Message.Contains("BBB"))
				{
					throw;
				}
				catch (Exception ex) when (ex.Message.Contains("AAA"))
				{
					throw;
				}
			}
	6.nameof 表达式 获取类型名称
            string className = nameof(StaticClass);
            string studentNmae = nameof(Student);
 7.新增属性发生变化 INotifyPropertyChanged 监听属性发布订阅
            NotifyPropertyChanged notify = new();
            notify.PropertyChanged += (object o,
           PropertyChangedEventArgs args) => { }; notify.name = "zhangpp"; public class NotifyPropertyChanged : INotifyPropertyChanged { public string Name { get { return name; } set { name = value;    PropertyChanged?.Invoke(this,
                 new PropertyChangedEventArgs(nameof(name))); } } public string name; public event PropertyChangedEventHandler PropertyChanged; }
8.使用索引器初始化关联集合
			
	 Dictionary<int, string> keys = 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"},
		 };

		 keys.Add(123, "加油吧");
		 keys.Remove(123, out string value);

  

标签:string,LastName,笔记,语法,student,new,Sharp,public,name
来源: https://www.cnblogs.com/James-net/p/15196665.html