• 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.

  • 相关阅读:
    以用户名注册来分析三种Action获取数据的方式
    Struts2中的OGNL详解 《转》
    Module 'null' not found异常解决办法
    struts标签<logic:iterate>的用法
    struts2的核心和工作原理 <转>
    jstl标签怎么实现分页中下一页
    forward 和redirect
    forward 和redirect的区别
    今天早上起来就想着要问问龙虎有圆通没
    昨天晚上回来弄了两个皮蛋吃
  • 原文地址:https://www.cnblogs.com/carlows/p/2781134.html
Copyright © 2020-2023  润新知