C# 2015 學習紀錄:如何處理數字與文字

By

變數、常數變數命名規則

  1. 「變數 Variable」命名可以依照 Camel Notation原則命名,也就是第一個英文字母小寫,後續接續的單字的第一個英文字母用大寫,例如:int counter = 1;、long numberOfBytes = 20000;、float interestRate = 8.125f;
  2. 「變數常數 Const Variable」命名可以依照 Pascal notation原則命名,也就是第一個英文字母大寫其餘小寫,例如:const int DaysInNovember = 30;、const decimal SalesTax = .075m;
  3. 各控制項的 Camel Notation命名參考方式可以到此網站瀏覽。

數值型態

C# 2015 提供 13種內建的數值型態,其中特別要注意的是float、decimal的宣告,必須在宣告型別、指定數值時,特別以文字「f」或「m」來特別表示其值屬於何種型別。

運算子與運算元

數學運算可以區分「二元運算子 Binary operators」與「一元運算子 Unary operators」,二元的意思便是像加減乘除或模數,都是需要兩個運算子(數字或變數)來搭配使用,像是1 + 1 =2 這樣。而一元則是只有一個運算子而已,像是正號+負號 - ,僅僅改變一個運算子的數值而已。

除法跟模數運算部分:

division (/) : If you’re working with integer data types, the division operator returns an interger value that represents the number of times the right operand goes into the left operand. Then, the modulus (%) operator returns an interger value that represents the remainder (which is the amount that’s left over after dividing the left operand by the right operand). If you working with non-integer data types, the division operator returns a value that uses decimal places to indicate the result of the division, which is usually what you want.
使用數學函數的方法:class.methodName ( one or more arguments) 例如:int shipWeight = Math.Round (shipWeightDouble);double orderTotal = Math.Round (orderTotal, 2);double area = Math.Pow (radius, 2) * Math.PI

字串與特殊字元

特殊字元的字串輸入我們遇到換行、Tab或需要雙引號的時候,在C#中有兩種方式可以提供我們使用:
  1. 「Escape Sequences」傳統上常使用的「\n」、「\t」、「\r」、「\\」、「\”」方式,用來當字串遇到反斜線、雙引號或是控制字元像是換行、Tab或Enter之類的的符號時。例如: string code = “JSPS”; decimal price = 49.50m; string result = “Code: “ + code + “\n” + “Price: $” + price + “\n; 輸出結果: Code: JSPS Price: $49.50
  2. 「Verbatim string literals」:只需要在字串的 “ “ 前加入「@」後,即可在字串中正常的使用各種特殊字元,但如果要使用雙引號「”」的話,必須在每一個「”」前多加一個「“」。例如: string path = @“c:\c#.net\files”; 輸出結果:c:\c#.net\files
因為「Escape Sequences」通常使用上比較簡單也比較容易插入字串,而「Verbatim string literals」則是方便在字串內隨意輸入特殊字元,通常也比較適合用來表達檔案目錄時,兩種表示特殊字元的方式都可以,端賴何種情況適合哪一種表示方式。

.NET結構與類別定義的資料類別

.NET提供了兩種資料類別的定義方式,分別是結構「 Structures」與類別「classes」,其中如果資料型態宣告的是由結構來源的變數,像是int, double等等,這些都屬「值」的型別,其變數存的資料真的就是那份資料,並且當複製或指派給另一個變數時,另一個變數是以複製的方式、創造另一個變數出來。而類別的資料型態像是String、Object,其儲存的是該String (Object)物件的參考值,也就是可以有多個變數可以共參考同一個字串或物件類別。

變數 & NULL

C#允許數值型態的資料類型可以有NULL值存在,命名方式係在宣告變數型別後立刻接上一個「?」表示其為一個可儲存NULL值的變數,例如:int? num = null;,我們可以利用屬性「HasValue」與「Value」測試該變數的值是否為NULL值,如果不是、那其值為何。

0 意見:

張貼留言