次の方法で共有


方法 : 構造体間にユーザー定義の変換を実装する (C# プログラミング ガイド)

この例では、RomanNumeral と BinaryNumeral の 2 つの構造体が定義されていて、これらの構造体間の変換を示しています。

使用例

struct RomanNumeral
{
    private int value;

    public RomanNumeral(int value)  //constructor
    {
        this.value = value;
    }

    static public implicit operator RomanNumeral(int value)
    {
        return new RomanNumeral(value);
    }

    static public implicit operator RomanNumeral(BinaryNumeral binary)
    {
        return new RomanNumeral((int)binary);
    }

    static public explicit operator int(RomanNumeral roman)
    {
        return roman.value;
    }

    static public implicit operator string(RomanNumeral roman)
    {
        return ("Conversion to string is not implemented");
    }
}

struct BinaryNumeral
{
    private int value;

    public BinaryNumeral(int value)  //constructor
    {
        this.value = value;
    }

    static public implicit operator BinaryNumeral(int value)
    {
        return new BinaryNumeral(value);
    }

    static public explicit operator int(BinaryNumeral binary)
    {
        return (binary.value);
    }

    static public implicit operator string(BinaryNumeral binary)
    {
        return ("Conversion to string is not implemented");
    }
}

class TestConversions
{
    static void Main()
    {
        RomanNumeral roman;
        BinaryNumeral binary;

        roman = 10;

        // Perform a conversion from a RomanNumeral to a BinaryNumeral:
        binary = (BinaryNumeral)(int)roman;

        // Perform a conversion from a BinaryNumeral to a RomanNumeral: 
        // No cast is required:
        roman = binary;

        System.Console.WriteLine((int)binary);
        System.Console.WriteLine(binary);

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    10
    Conversion not yet implemented
*/

信頼性の高いプログラミング

  • 前述の例の次のステートメントは、

    binary = (BinaryNumeral)(int)roman;
    

    このステートメントは、RomanNumeral から BinaryNumeral への変換を実行します。 RomanNumeral から BinaryNumeral への直接変換はないため、RomanNumeral から int へ変換するためのキャストと、int から BinaryNumeral へ変換するためのキャストが使用されています。

  • また、次のステートメントは、

    roman = binary;
    

    BinaryNumeral から RomanNumeral への変換を実行します。 RomanNumeral は BinaryNumeral からの暗黙の型変換を定義しているため、キャストは不要です。

参照

関連項目

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

概念

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

その他の技術情報

C# リファレンス