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.

  • 相关阅读:
    ORACLE创建、修改、删除序列
    mysql添加索引
    Mysql事物与Metadata lock 问题
    oracle 查询最近执行过的 SQL语句
    ORACLE 常用SQL查询
    ssh-keygen的用法
    sql之left join、right join、inner join的区别
    Linux下使用 ipset 封大量IP及ipset参数说明
    今天学习的小命令
    Linux下查看分区内目录及文件占用空间容量
  • 原文地址:https://www.cnblogs.com/carlows/p/2781134.html
Copyright © 2011-2022 走看看