zoukankan      html  css  js  c++  java
  • C#转换运算符explicit和implicit

    第一种explicit,显式转换

    struct Digit
    {
        byte value;

        public Digit(byte value)  //constructor
        {
            if (value > 9)
            {
                throw new System.ArgumentException();
            }
            this.value = value;
        }

        public static explicit operator Digit(byte b)  // explicit byte to digit conversion operator
        {
            Digit d = new Digit(b);  // explicit conversion

            System.Console.WriteLine("Conversion occurred.");
            return d;
        }
    }

    class TestExplicitConversion
    {
        static void Main()
        {
            try
            {
                byte b = 3;
                Digit d = (Digit)b;  // explicit conversion 这里会显式的调用Digit(byte b)通过该方法将byte类型的b转换成Digit类型,这属于强制转换
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("{0} Exception caught.", e);
            }
        }
    }

    第二种implicit,隐式转换

    struct Digit
    {
        byte value;

        public Digit(byte value)  //constructor
        {
            if (value > 9)
            {
                throw new System.ArgumentException();
            }
            this.value = value;
        }

        public static implicit operator byte(Digit d)  // implicit digit to byte conversion operator
        {
            System.Console.WriteLine("conversion occurred");
            return d.value;  // implicit conversion
        }
    }

    class TestImplicitConversion
    {
        static void Main()
        {
            Digit d = new Digit(3);
            byte b = d;  // implicit conversion -- no cast needed
        }
    }
    // Output: Conversion occurred.

  • 相关阅读:
    Linux 之 编译器 gcc/g++参数详解
    linux下history命令显示历史指令记录的使用方法
    Linux 命令之 Navicat 连接 Linux 下的Mysql数据库
    Linux命令
    CentOS 下安装
    CMD命令之 :修改windows的CMD窗口输出编码格式为UTF-8
    CTO、技术总监、首席架构师的区别
    PHP ServerPush (推送) 技术的探讨
    一个公司的管理层级结构
    Table of Contents
  • 原文地址:https://www.cnblogs.com/carlows/p/2781134.html
Copyright © 2011-2022 走看看