1 using System; 2 3 namespace ConsoleApp1 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 10 { 11 Student student = new Student("蛋蛋", "張"); 12 13 Console.WriteLine(student.ToString()); 14 15 student.Show(); 16 } 17 18 { 19 //條件運算子 20 Student student1 = null; 21 22 //1. 得到的結果一定要支持null 23 //2. 如果 student1 是 null,回傳 null,如果 student1 有值 就回傳 student1.FirstName 24 string fullName = student1?.FirstName; 25 26 //必須為可空型別,如果是 int id = student1?.Id; 則報錯 27 int? id = student1?.Id; 28 29 Console.WriteLine("Hello World!"); 30 31 student1 = new Student("AA", "BB"); 32 fullName = student1?.FullName1; 33 34 //1. 判斷student1是否為null,如果為null,直接回傳null; 35 //2. 如果不為null,判斷 student1.FullName1 是否為null,如果為null,回傳“張三”,如果不為null,回傳 student1.FullName1 36 string testName = student1?.TestName ?? "張三"; 37 } 38 39 //字串內插 40 { 41 string firstName = "蛋蛋"; 42 string lastName = "張"; 43 string strs = $"{{{lastName}}}-{firstName}"; //結果:{張}-蛋蛋 44 } 45 46 //例外篩選器 47 { 48 try 49 { 50 throw new Exception("我是張蛋蛋的好朋友!"); 51 }catch(Exception ex) when(ex.Message.Contains("張蛋蛋")) 52 { 53 Console.WriteLine("如果例外Message字串中包含‘張蛋蛋’,那么就會顯示此段話!"); 54 //throw; 55 } 56 } 57 //nameof 運算式 58 { 59 60 string className = nameof(Student); 61 Console.WriteLine($"獲取到類名稱:{className}"); 62 } 63 64 } 65 } 66 }Program 類
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 namespace ConsoleApp1 6 { 7 public class Student 8 { 9 public Student(string firstName,string lastName) 10 { 11 FirstName = firstName; 12 LastName = lastName; 13 } 14 15 public int? Id { get; set; } 16 public string TestName { get; set; } 17 18 /// <summary> 19 /// 只能通過建構式賦值 20 /// </summary> 21 public string FirstName { get; } 22 public string LastName { get; } 23 24 /// <summary> 25 /// FullName1 與 FullName2 功能相同 26 /// </summary> 27 public string FullName1 28 { 29 get 30 { 31 return string.Format("{0}-{1}", this.FirstName, this.LastName); 32 } 33 } 34 35 public string FullName2=> string.Format("{0}-{1}", this.FirstName, this.LastName);//念 goes to 36 37 public void Show() 38 { 39 Console.WriteLine(string.Format("FullName1:{0}",FullName1)); 40 Console.WriteLine(string.Format("FullName2:{0}", FullName2)); 41 } 42 43 /// <summary> 44 /// 方法A (方法A與方法B功能相同) 45 /// </summary> 46 /// <returns></returns> 47 public override string ToString() => string.Format("我是方法:{0}-{1}", this.FirstName, this.LastName);//念 goes to 48 /// <summary> 49 /// 方法B 50 /// </summary> 51 /// <returns></returns> 52 //public override string ToString() 53 //{ 54 // return string.Format("我是方法:{0}-{1}", this.FirstName, this.LastName); 55 //} 56 57 } 58 }Student 類
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/266175.html
標籤:C#
上一篇:C#連接Excel讀取與寫入資料庫SQL ( 上 )
下一篇:一日一技:微信開發-自定義選單
