Csharp/CSharp Tutorial/Operator Overload/Implicit Conversion Operator

Материал из .Net Framework эксперт
Версия от 12:18, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

An example that uses an implicit conversion operator.

using System; 
 
class TwoDimension { 
  int x, y;
 
  public TwoDimension() { 
     x = y = 0; 
  } 
  public TwoDimension(int i, int j) { 
     x = i; 
     y = j;
  } 
 
  // Overload binary +. 
  public static TwoDimension operator +(TwoDimension op1, TwoDimension op2) 
  { 
    TwoDimension result = new TwoDimension(); 
 
    result.x = op1.x + op2.x;  
    result.y = op1.y + op2.y;  
 
    return result; 
  } 
 
  // An implicit conversion from TwoDimension to int. 
  public static implicit operator int(TwoDimension op1) 
  { 
    return op1.x * op1.y; 
  } 
   
  // Show X, Y
  public void show() 
  { 
    Console.WriteLine(x + ", " + y); 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    TwoDimension a = new TwoDimension(1, 2); 
    TwoDimension b = new TwoDimension(10, 10); 
    TwoDimension c = new TwoDimension(); 
    int i; 
 
    Console.Write("Here is a: "); 
    a.show(); 
    Console.WriteLine(); 
    Console.Write("Here is b: "); 
    b.show(); 
    Console.WriteLine(); 
 
    c = a + b; // add a and b together 
    Console.Write("Result of a + b: "); 
    c.show(); 
    Console.WriteLine(); 
 
    i = a; // convert to int 
    Console.WriteLine("Result of i = a: " + i); 
    Console.WriteLine(); 
 
    i = a * 2 - b; // convert to int 
    Console.WriteLine("result of a * 2 - b: " + i); 
  } 
}
Here is a: 1, 2
Here is b: 10, 10
Result of a + b: 11, 12
Result of i = a: 2
result of a * 2 - b: -96

Defining an Implicit Conversion

class Point
{
    public int X;
    public int Y;
   
    public static implicit operator double(Point RValue)
    {
        double Distance;
        double Sum;
   
        Sum = (RValue.X * RValue.X) + (RValue.Y * RValue.Y);
        Distance = System.Math.Sqrt(Sum);
        return Distance;
    }
   
    public static void Main()
    {
        double Distance;
        Point MyPoint = new Point();
   
        MyPoint.X = 100;
        MyPoint.Y = 200;
        Distance = MyPoint;
        System.Console.WriteLine(Distance);
    }
}