implicit(C# 參考)

來源:互聯網
上載者:User
implicit 關鍵字用於聲明隱式的使用者定義型別轉換運算子。如果可以確保轉換過程不會造成資料丟失,則可使用該關鍵字在使用者定義型別和其他類型之間進行隱式轉換。
樣本
C#
class Digit
{
public Digit(double d) { val = d; }
public double val;
// ...other members

// User-defined conversion from Digit to double
public static implicit operator double(Digit d)
{
return d.val;
}
// User-defined conversion from double to Digit
public static implicit operator Digit(double d)
{
return new Digit(d);
}
}
class Program
{
static void Main(string[] args)
{
Digit dig = new Digit(7);
//This call invokes the implicit "double" operator
double num = dig;
//This call invokes the implicit "Digit" operator
Digit dig2 = 12;
Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val);
Console.ReadLine();
}
}
}

隱式轉換可以通過消除不必要的類型轉換來提高原始碼的可讀性。但是,因為隱式轉換不需要程式員將一種類型顯式強制轉換為另一種類型,所以使用隱式轉換時必須格外小心,以免出現意外結果。一般情況下,隱式轉換運算子應當從不引發異常並且從不丟失資訊,以便可以在程式員不知曉的情況下安全使用它們。如果轉換運算子不能滿足那些條件,則應將其標記為 explicit。有關更多資訊,請參見使用轉換運算子。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.