Thứ Hai, ngày 25 tháng 1 năm 2010

// // Leave a Comment

operator Keyword C#



The operator keyword allows a class to overload arithmetic and cast operators:
public class Complex
{
private double re, im;

public double Real
{
get { return re; }
set { re = value; }
}

public double Imaginary
{
get { return im; }
set { im = value; }
}

// binary operator overloading
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex()
{
Real = c1.Real + c2.Real, Imaginary = c1.Imaginary + c2.Imaginary };
}

// unary operator overloading
public static Complex operator -(Complex c)
{
return new Complex() { Real = -c.Real, Imaginary = -c.Imaginary };
}

// cast operator overloading (both implicit and explicit)
public static implicit operator double(Complex c)
{
// return the modulus: sqrt(x^2 + y^2)
return Math.Sqrt(Math.Pow(c.Real, 2) + Math.Pow(c.Imaginary, 2));
}

public static explicit operator string(Complex c)
{
// we should be overloading the ToString() method, but this is just a demonstration
return c.Real.ToString() + " + " + c.Imaginary.ToString() + "i";
}
}

public class StaticDemo
{
public static void Main()
{
Complex number1 = new Complex() { Real = 1, Imaginary = 2 };
Complex number2 = new Complex() { Real = 4, Imaginary = 10 };
Complex number3 = number1 + number2; // number3 now has Real = 5, Imaginary = 12

number3 = -number3; // number3 now has Real = -5, Imaginary = -12
double testNumber = number3; // testNumber will be set to the absolute value of number3
Console.WriteLine((string)number3); // This will print "-5 + -12i".
// The cast to string was needed because that was an explicit cast operator.

0 comments: