實值型別轉換的幾種方式

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

參考型別的轉換方式有隱式轉換、強制轉換、as轉換等。實值型別的轉換方式也有不少,本篇稍稍歸納。


□ 隱式轉換

 

int i = 10;
float f = i;
Console.WriteLine(f);

如果是實值型別,當被轉換變數的數值範圍小於目標變數的數值範圍,就可以實現隱式轉換;如果是參考型別,子類可以隱式轉換成父類。

 

□ 強制轉換

 

float f = 10.56f;
int i = (int) f;
Console.WriteLine(i);

如果是實值型別,當被轉換變數的數值範圍大於目標變數的數組範圍,考慮使用強制轉換;如果是參考型別,父類可以強制轉換成某個子類。值得注意的是:強制轉換可能會導致損失一些精度。

 

□ 通過System.Convert的靜態方法實施轉換

 

比如把一個整型轉換成Sysem.Char類型。

char result = Convert.ToChar(68);
Console.WriteLine(result);

通過System.Convert轉換失敗會報OverflowException異常。

 

□ 通過實值型別的靜態方法

 

把字串轉換成int類型。

string str = "11";
int i = int.Parse(str);
Console.WriteLine(i);

 

如果字串中包含非數字,會拋出System.FormatException異常。

string str = "11a";
int i = int.Parse(str);
Console.WriteLine(i);

 

如何避免這種情況呢?
--使用int.TryParse方法可以避免這種情況。

 

string str = "11a";
int result = 1;
bool isSuccess = int.TryParse(str, out result);
if (isSuccess)
{
    Console.WriteLine(result);
}
else
{
    Console.WriteLine("轉換失敗");
}


           

□ 通過IConvertible介面方法

 

由於所有的實值型別都實現了IConvertible介面,可以通過該介面的方法實現實值型別轉換。

char result =  ((IConvertible) 68).ToChar(null);
Console.WriteLine(result);

如果轉換失敗,會拋出System.InvalidCastException異常。

 

 

實值型別轉換的幾種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.