Csharp/CSharp Tutorial/Operator Overload/Explicit Conversion Operator

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Use an explicit conversion.

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; 
  } 
 
  // This is now explicit. 
  public static explicit 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 = (int) a; // explicitly convert to int -- cast required 
    Console.WriteLine("Result of i = a: " + i); 
    Console.WriteLine(); 
 
    i = (int)a * 2 - (int)b; // casts required 
    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