C#explicit和implicit关键字实现类型转换

using System;


namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //implicit 隐式装换
            Digit dig1 = new Digit(7.0m);
            decimal num = dig1;
            Digit dig2 = 12.0m;
            Console.WriteLine("num = {0} dig2 = {1}", num, dig2.Val);

            //explicit 显示转换
            AA a1 = new AA
            {
                A = "A",
                B = 1,
                C = 1.0m
            };

            BB b1 = new BB
            {
                A1 = "B",
                B1 = 2,
                C1 = 2.0m
            };
            AA a2 = (AA)b1;
            BB b2 = (BB)a1;
            Console.WriteLine($"{a2.A}|{a2.B}|{a2.C}");
            Console.WriteLine($"{b2.A1}|{b2.B1}|{b2.C1}");
            Console.ReadLine();
        }
    }

    class Digit
    {
        public decimal Val;
        public Digit(decimal d) { Val = d; }
        public static implicit operator decimal(Digit d)
        {
            return d.Val;
        }
        public static implicit operator Digit(decimal d)
        {
            return new Digit(d);
        }
    }

    class AA
    {
        public string A { get; set; }
        public int B { get; set; }
        public decimal C { get; set; }

        public static explicit operator BB(AA c)
        {
            return new BB
            {
                A1 = c.A,
                B1 = c.B,
                C1 = c.C
            };
        }
    }

    class BB
    {
        public string A1 { get; set; }
        public int B1 { get; set; }
        public decimal C1 { get; set; }
        public static explicit operator AA(BB c)
        {
            return new AA
            {
                A = c.A1,
                B = c.B1,
                C = c.C1
            };
        }
    }

}

 

C#explicit和implicit关键字实现类型转换

上一篇:windows7 10 windows2008 windws2012 nfs客户端的安装


下一篇:Permission denied (publickey,gssapi-keyex,gssapi-with-mic).错误的解决