Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Реализация определенных пользователем преобразований между структурами

В данном примере определяются две структуры RomanNumeral и BinaryNumeral и демонстрируется преобразование между ними.

Пример

---

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);

}

}

10

Conversion not yet implemented

----

Robust Programming

  • In the previous example, the statement:

    binary = (BinaryNumeral)(int)roman;

  • performs a conversion from a RomanNumeral to a BinaryNumeral. Because there is no direct conversion from RomanNumeral to BinaryNumeral, a cast is used to convert from a RomanNumeral to an int, and another cast to convert from an int to a BinaryNumeral.

  • Also the statement

    roman = binary;

  • performs a conversion from a BinaryNumeral to a RomanNumeral. Because RomanNumeral defines an implicit conversion from BinaryNumeral, no cast is required.

Надежное программирование

  • В предыдущем примере оператор

    binary = (BinaryNumeral)(int)roman;

  • выполняет преобразование из RomanNumeral в BinaryNumeral. Поскольку прямого преобразования из RomanNumeral в BinaryNumeral не существует, используется приведение для преобразования из RomanNumeral в int и другое приведение для преобразования из int в BinaryNumeral.

  • Кроме того, оператор

    roman = binary;

  • выполняет преобразование из BinaryNumeral в RomanNumeral. Поскольку RomanNumeral определяет неявное преобразование из BinaryNumeral, приведение не требуется.

How to: Use Operator Overloading to Create a Complex Number Class

This example shows how you can use operator overloading to create a complex number class Complex that defines complex addition. The program displays the imaginary and the real parts of the numbers and the addition result using an override of the ToString method.

Example

public struct Complex

{

public int real;

public int imaginary;

public Complex(int real, int imaginary) //constructor

{

this.real = real;

this.imaginary = imaginary;

}

// Declare which operator to overload (+),

// the types that can be added (two Complex objects),

// and the return type (Complex):

public static Complex operator +(Complex c1, Complex c2)

{

return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);

}

// Override the ToString() method to display a complex number in the traditional format:

public override string ToString()

{

return (System.String.Format("{0} + {1}i", real, imaginary));

}

}

class TestComplex

{

static void Main()

{

Complex num1 = new Complex(2, 3);

Complex num2 = new Complex(3, 4);

// Add two Complex objects through the overloaded plus operator:

Complex sum = num1 + num2;

// Print the numbers and the sum using the overriden ToString method:

System.Console.WriteLine("First complex number: {0}", num1);

System.Console.WriteLine("Second complex number: {0}", num2);

System.Console.WriteLine("The sum of the two numbers: {0}", sum);

}

}

First complex number: 2 + 3i

Second complex number: 3 + 4i

The sum of the two numbers: 5 + 7i