隐式转换运算符(implicit)

作者:追风剑情 发布于:2015-10-15 15:00 分类:C#

以下是官方示例

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);
        }
    }
}

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号