explicit (C# 參考)

explicit 關鍵字會宣告必須以轉型 (cast) 叫用的使用者定義型別轉換運算子。 例如,此運算子會從名為 Fahrenheit 的類別轉換成名為 Celsius 的類別:

// Must be defined inside a class called Farenheit:
public static explicit operator Celsius(Fahrenheit f)
{
    return new Celsius((5.0f / 9.0f) * (f.degrees - 32));
}

可以如下所示的方式叫用轉換運算子:

Fahrenheit f = new Fahrenheit(100.0f);
Console.Write("{0} fahrenheit", f.Degrees);
Celsius c = (Celsius)f;

轉換運算子會從來源型別轉換成目標型別。 來源型別會提供轉換運算子。 不同於隱含轉換,明確轉換運算子必須經由轉型 (Cast) 的方式叫用。 若轉換作業會造成例外狀況或遺失資訊,您應將其標記為 explicit。 這可以防止編譯器在不顯示任何訊息下叫用轉換作業,而引發不可預知的後果。

省略轉型會導致編譯時期錯誤 CS0266。

如需詳細資訊,請參閱使用轉換運算子 (C# 程式設計手冊)

範例

下列範例提供 Fahrenheit 和 Celsius 類別,這兩個類別都提供了明確轉換運算子給其他類別。


class Celsius
{
    public Celsius(float temp)
    {
        degrees = temp;
    }
    public static explicit operator Fahrenheit(Celsius c)
    {
        return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
    }
    public float Degrees
    {
        get { return degrees; }
    }
    private float degrees;
}

class Fahrenheit
{
    public Fahrenheit(float temp)
    {
        degrees = temp;
    }
    // Must be defined inside a class called Farenheit:
    public static explicit operator Celsius(Fahrenheit f)
    {
        return new Celsius((5.0f / 9.0f) * (f.degrees - 32));
    }
    public float Degrees
    {
        get { return degrees; }
    }
    private float degrees;
}

class MainClass
{
    static void Main()
    {
        Fahrenheit f = new Fahrenheit(100.0f);
        Console.Write("{0} fahrenheit", f.Degrees);
        Celsius c = (Celsius)f;

        Console.Write(" = {0} celsius", c.Degrees);
        Fahrenheit f2 = (Fahrenheit)c;
        Console.WriteLine(" = {0} fahrenheit", f2.Degrees);
    }
}
/*
Output:
100 fahrenheit = 37.77778 celsius = 100 fahrenheit
*/

下面的範例定義了結構 Digit,代表了一個單一的十進位數字。 並定義一個可以將 byte 轉換為 Digit 的運算子,但由於不是所有的位元組都可以轉換成 Digit,故此轉換為明確。

struct Digit
{
    byte value;
    public Digit(byte value)
    {
        if (value > 9)
        {
            throw new ArgumentException();
        }
        this.value = value;
    }

    // Define explicit byte-to-Digit conversion operator:
    public static explicit operator Digit(byte b)
    {
        Digit d = new Digit(b);
        Console.WriteLine("conversion occurred");
        return d;
    }
}

class ExplicitTest
{
    static void Main()
    {
        try
        {
            byte b = 3;
            Digit d = (Digit)b; // explicit conversion
        }
        catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught.", e);
        }
    }
}
/*
Output:
conversion occurred
*/

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和用法的決定性來源。

請參閱

工作

HOW TO:在結構之間實作使用者定義的轉換 (C# 程式設計手冊)

參考

C# 關鍵字

implicit (C# 參考)

operator (C# 參考)

概念

C# 程式設計手冊

其他資源

C# 參考

C# 中鏈結的使用者定義明確轉換