HOW TO:在結構之間實作使用者定義的轉換 (C# 程式設計手冊)
更新:2007 年 11 月
本範例定義兩個結構:RomanNumeral 和 BinaryNumeral,並說明它們之間的轉換。
範例
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
*/
穩固程式設計
在前面的範例中,陳述式:
binary = (BinaryNumeral)(int)roman;
會執行轉換,從 RomanNumeral 轉換為 BinaryNumeral。因為 RomanNumeral 和 BinaryNumeral 之間並沒有直接轉換,所以使用型別轉換以將 RomanNumeral 轉換成 int,並且使用另一個型別轉換以將 int 轉換成 BinaryNumeral。
同時,陳述式
roman = binary;
會執行轉換,從 BinaryNumeral 轉換為 RomanNumeral。因為 RomanNumeral 定義了一個從 BinaryNumeral 轉換的隱含轉換,所以不需要轉換。