zoukankan      html  css  js  c++  java
  • 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
                };
            }
        }
    
    }
  • 相关阅读:
    Spring Boot 搭建项目阶段Group和Artifact的含义
    设置Mysql数据库账号密码以及时区
    反射
    线程与进程
    网络编程
    队列和栈
    linux下的mysql
    积累的关于linux的安装卸载软件基本命令
    各种url编码
    解决浏览器传值乱码
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/10948483.html
Copyright © 2011-2022 走看看