更新:2007 年 11 月

本示例定义 RomanNumeralBinaryNumeral 两个结构,并演示二者之间的转换。

示例

C# 复制代码
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 not yet 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 not yet 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
*/

可靠编程

  • 在上面的示例中,语句:

    C# 复制代码
    binary = (BinaryNumeral)(int)roman;
    
    

    执行从 RomanNumeralBinaryNumeral 的转换。由于没有从 RomanNumeralBinaryNumeral 的直接转换,所以使用一个转换将 RomanNumeral 转换为 int,并使用另一个转换将 int 转换为 BinaryNumeral

  • 另外,语句

    C# 复制代码
    roman = binary;
    
    

    执行从 BinaryNumeralRomanNumeral 的转换。由于 RomanNumeral 定义了从 BinaryNumeral 的隐式转换,所以不需要转换。

请参见