鸟语天空
隐式转换运算符(implicit)
post by:追风剑情 2015-10-15 15:00

以下是官方示例

using System;

namespace ImplicitTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Digit dig = new Digit(7);
            //调用隐式转换double操作符
            double num = dig;
            //调用隐式转换Digit操作符
            Digit dig2 = 12;
            Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val);
            Console.ReadLine();
        }
    }

    class Digit
    {
        public Digit(double d) { val = d; }
        public double val;

        // Digit转double
        public static implicit operator double(Digit d)
        {
            return d.val;
        }
        //  double转Digit
        public static implicit operator Digit(double d)
        {
            return new Digit(d);
        }
    }
}

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容