Console.WriteLine($\"decimal: {myDecimal}\");
int myInt = (int)myDecimal;
Console.WriteLine($\"int: {myInt}\");\n
上述為將常用於科學數值的 decimal 轉換成 int,因此會出現位數流失的問題。
\n使用此方法將數字轉換成字串,雖然並非必要手段,但可以讓其他程式員了解我們在幹嘛。
\n大部分的數值資料類型都擁有此方法,它會將字串轉換成城指定的資料類型,譬如:將兩個string轉換成int,不過如果遇到無法轉換的情況會出問題。
\n\nint.parse(string);
此類別將字串轉換成數字
\n\nstring value1 = \"5\";
string value2 = \"7\";
int result = Convert.ToInt32(value1) * Convert.ToInt32(value2);
Console.WriteLine(result);
如果是放大轉換,可以依賴編譯器來執行轉換,不過如果是縮小轉換就會需要使用Convert類別,當確定轉換沒有問題時,可以使用轉換運算子。
\n將字串資料轉換成數值資料,避免轉換資料類型造成執行階段的錯誤,例如:
\n\nstring name = \"Bob\";
Console.WriteLine(int.Parse(name));
會跳以下錯誤
\n\nSystem.FormatException: 'Input string was not in a correct format.'
在所有數值資料類型上都可以使用:
\n方法可返回值或返回void,方法還可以透過out參數返回值,定義與輸入參數相同但包含關鍵字out。
\n使用out參數調用方法時,必須在變量前使用關鍵字out來保存值,並可在代碼其他部分使用。
\n\nstring value = \"102\";
int result = 0;
if (int.TryParse(value, out result))
{
Console.WriteLine($\"Measurement: {result}\");
}
else
{
Console.WriteLine(\"Unable to report the measurement.\");
}
其中關注這一行
\n\nif (int.TryParse(value, out result))
如果int.TryParse()方法將string變數value轉換成int,則會傳回 true;否則會傳回 false,故將此陳述式包圍在 if 陳述式中,並根據該陳述式執行決策邏輯。
\n其中,轉換後的值會儲存在result,簡單來說,int.TryParse()會回傳bool,它的作用是把左邊的值轉換成int儲存在右邊,失敗False成功True。
\n特殊之處在於,這個result可以同時透過程式碼區塊內部和外部存取,所以out關鍵字會指示編譯器雙向參數傳達輸出。
\n在程式設計中,c#被稱為是安全穩定的程式,那這個安全穩定的方式來源在哪裡呢?我覺得跟資料型態的嚴謹有關係,在資料型態上可以看到很多介紹,撰寫程式時也會因為資料型態而糾結很久,但熟悉以後,這些東西會加快撰寫效率和方便性。
\ndecimal myDecimal = 3.14m;
Console.WriteLine($"decimal: {myDecimal}");
int myInt = (int)myDecimal;
Console.WriteLine($"int: {myInt}");
int.parse(string);
string value1 = "5";
string value2 = "7";
int result = Convert.ToInt32(value1) * Convert.ToInt32(value2);
Console.WriteLine(result);
string name = "Bob";
Console.WriteLine(int.Parse(name));
System.FormatException: 'Input string was not in a correct format.'
string value = "102";
int result = 0;
if (int.TryParse(value, out result))
{
Console.WriteLine($"Measurement: {result}");
}
else
{
Console.WriteLine("Unable to report the measurement.");
}
if (int.TryParse(value, out result))