変換演算子の使用 (C# プログラミング ガイド)

更新 : 2007 年 11 月

変換演算子は、explicit の形式にも implicit の形式にもできます。暗黙の変換演算子の方が簡単に使用できますが、変換中であることを演算子のユーザーが認識できるようにするには、明示的な演算子が便利です。このトピックでは、両方の型について説明します。

使用例

ここでは、明示的な変換演算子の例を示します。この演算子は、Byte 型を Digit という値型に変換します。すべての byte 型を Digit 型に変換できるとは限らないため、変換は明示的に行うように指定されています。つまり、Main メソッドに示すように、キャストを使用する必要があります。

struct Digit
{
    byte value;

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

    public static explicit operator Digit(byte b)  // explicit byte to digit conversion operator
    {
        Digit d = new Digit(b);  // explicit conversion

        System.Console.WriteLine("Conversion occurred.");
        return d;
    }
}

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

この例は、上の例で行った処理を元に戻す変換演算子を定義することにより、暗黙の変換演算子を示しています。この例では、Digit という値クラスを整数 Byte 型に変換します。すべての Digit 型を Byte に変換できるため、変換をユーザーに明示する必要はありません。

struct Digit
{
    byte value;

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

    public static implicit operator byte(Digit d)  // implicit digit to byte conversion operator
    {
        System.Console.WriteLine("conversion occurred");
        return d.value;  // implicit conversion
    }
}

class TestImplicitConversion
{
    static void Main()
    {
        Digit d = new Digit(3);
        byte b = d;  // implicit conversion -- no cast needed
    }
}
// Output: Conversion occurred.

参照

概念

C# プログラミング ガイド

参照

変換演算子 (C# プログラミング ガイド)

その他の技術情報

C# リファレンス