implicit (C# 參考)implicit (C# Reference)

implicit 關鍵字是用來宣告隱含的使用者定義型別轉換運算子。The implicit keyword is used to declare an implicit user-defined type conversion operator. 使用它可啟用使用者定義型別和其他型別之間的隱含轉換,但前提是要保證轉換作業不會導致資料的遺失。Use it to enable implicit conversions between a user-defined type and another type, if the conversion is guaranteed not to cause a loss of data.


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);

隱含轉換藉由消除不必要的轉換,來改善原始程式碼的可讀性。By eliminating unnecessary casts, implicit conversions can improve source code readability. 不過,由於隱含轉換不需要程式設計人員將某個類型明確轉換為另一個類型,因此必須謹慎使用,以避免產生非預期的結果。However, because implicit conversions do not require programmers to explicitly cast from one type to the other, care must be taken to prevent unexpected results. 一般而言,隱含轉換運算子絕對不會擲回例外狀況,也絕對不會遺失資訊,因此即使程式設計人員沒有注意也可以安全地使用。In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness. 如果轉換運算子無法符合這些準則,則應該將其標記為 explicitIf a conversion operator cannot meet those criteria, it should be marked explicit. 如需詳細資訊,請參閱使用轉換運算子For more information, see Using Conversion Operators.

C# 語言規格C# language specification

如需詳細資訊,請參閱<C# 語言規格>。For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also