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.

  • 相关阅读:
    winsows10 小技巧
    数组与智能指针
    卸载 VS2015
    Effective C++
    修改 git commit 的信息
    线程管理
    并发编程简介
    个别算法详解
    git 删除某个中间提交版本
    git 查看某一行代码的修改历史
  • 原文地址:https://www.cnblogs.com/carlows/p/2781134.html
Copyright © 2011-2022 走看看