C# 靈活用法拾遺

一、switch case :函數

 1 int a = 3;
 2 switch (a)
 3 {
 4      case 1:
 5         Console.WriteLine("");
 6         break;
 7      case 2:
 8      case 3:
 9         Console.WriteLine("二或三");
10         break;
11 }

二、for循環 :學習

for(<初始條件>; <判斷條件>; <更新條件>)spa

{code

     <代碼塊>blog

}get

1 double d;
2  for (string x = Console.ReadLine(); double.TryParse(x, out d); x = Console.ReadLine())
3 {
4     Console.WriteLine("您輸入的數字是:{0}\n", d);
5 }

 

三、函數調用string

調用方法是能夠標註參數對應的值,標註同時,能夠不按方法參數表順序傳參:it

1 static int Add(int a, int b)
2 {
3     return a + b;
4 }
5 static void Main(string[] args)
6 {
7     int c = Add(3, 5);
8     int d = Add(b: 5, a: 3);
9 }

四、引用類型for循環

 1 public class Person
 2 {
 3     public string Name { get; set; }
 4     public int Age { get; set; }
 5 }
 6 
 7 class Program
 8 {
 9     static void Main(string[] args)
10     {
11        // 建立 ps1, 並實例化ps1
12        Person ps1 = new Person { Name = "Tim", Age = 22 };
13        // 建立ps2用ps1給ps2賦值
14        Person ps2 = ps1;
15        Console.WriteLine("ps1被修改前ps2的值:\nps2.Name = {0}, ps2.Age = {1}", ps2.Name, ps2.Age);
16 
17       // 修改ps1的值
18       ps1.Name = "Jack";
19       ps1.Age = 18;
20       // 修改ps1後,ps2的值
21       Console.WriteLine("修改ps1後,ps2的值:\nps2.Name = {0}, ps2.Age = {1}", ps2.Name, ps2.Age);
22     } 
23 }

輸出:class

ps1被修改前ps2的值:
ps2.Name = Tim, ps2.Age = 22
修改ps1後,ps2的值:
ps2.Name = Jack, ps2.Age = 18

 

五、值類型

 

 1  public struct Person
 2 {
 3     public string Name { get; set; }
 4     public int Age { get; set; }
 5 }
 6  class Program
 7 {
 8     static void Main(string[] args)
 9     {
10          // 建立 ps1, 並實例化ps1
11          Person ps1 = new Person { Name = "Tim", Age = 22 };
12          // 建立ps2用ps1給ps2賦值
13          Person ps2 = ps1;
14          Console.WriteLine("ps1被修改前ps2的值:\nps2.Name = {0}, ps2.Age = {1}", ps2.Name, ps2.Age);
15 
16          // 修改ps1的值
17          ps1.Name = "Jack";
18          ps1.Age = 18;
19          // 修改ps1後,ps2的值
20          Console.WriteLine("修改ps1後,ps2的值:\nps2.Name = {0}, ps2.Age = {1}", ps2.Name, ps2.Age);
21     } 
22 }

輸出:

ps1被修改前ps2的值:
ps2.Name = Tim, ps2.Age = 22
修改ps1後,ps2的值:
ps2.Name = Tim, ps2.Age = 22

 

 

 

 

 

 

摘自《C# 6.0 學習筆記》

相關文章
相關標籤/搜索