Csharp/CSharp Tutorial/Operator Overload/Cast operator — различия между версиями

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

Текущая версия на 12:18, 26 мая 2010

explicit/implicit operator for Complex

using System;
public struct Complex
{
    public Complex( double real, double imaginary ) {
        this.real = real;
        this.imaginary = imaginary;
    }
    // System.Object override
    public override string ToString() {
        return String.Format( "({0}, {1})", real, imaginary );
    }
    public double Magnitude {
        get {
            return Math.Sqrt( Math.Pow(this.real, 2) + Math.Pow(this.imaginary, 2) );
        }
    }
    public static implicit operator Complex( double d ) {
        return new Complex( d, 0 );
    }
    public static explicit operator double( Complex c ) {
        return c.Magnitude;
    }
    private double real;
    private double imaginary;
}
public class EntryPoint
{
    static void Main() {
        Complex cpx1 = new Complex( 1.0, 3.0 );
        Complex cpx2 = 2.0;         // Use implicit operator.
        double d = (double) cpx1;   // Use explicit operator.
        Console.WriteLine( "cpx1 = {0}", cpx1 );
        Console.WriteLine( "cpx2 = {0}", cpx2 );
        Console.WriteLine( "d = {0}", d );
    }
}
cpx1 = (1, 3)
cpx2 = (2, 0)
d = 3.16227766016838

implicit and explicit operator cast

using System;
    class MyType
    {
        int value;
        public MyType( int b )
        {
            value = b;
        }
        public static implicit operator int( MyType a )
        {
            return a.value;
        }
        public static explicit operator string( MyType a )
        {
            return "$" + a.value;
        }
        static void Main(string[] args)
        {
            MyType bal = new MyType( 777 );
            Console.WriteLine("since int conversion is implicit we can write");
            int i = bal;
            Console.WriteLine("string conveersion must be explicitly requested");
            string str = (string)bal;
            // this causes a compilation error
            // str = bal;
            System.Console.WriteLine( "i = {0} \nstr = {1}", i, str );
        }
    }
since int conversion is implicit we can write
string conveersion must be explicitly requested
i = 777
str = $777