zoukankan      html  css  js  c++  java
  • implicit和 explicit关键字

    implicit 关键字用于声明隐式的用户定义类型转换运算符。 如果可以确保转换过程不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换。

    class Digit
    {
        public Digit(double d) { val = d; }
        public double val;
        // ...other members
    
        // User-defined conversion from Digit to double
        public static implicit operator double(Digit d)
        {
            return d.val;
        }
        //  User-defined conversion from double to Digit
        public static implicit operator Digit(double d)
        {
            return new Digit(d);
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Digit dig = new Digit(7);
            //This call invokes the implicit "double" operator
            double num = dig;
            //This call invokes the implicit "Digit" operator
            Digit dig2 = 12;
            Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val);
            Console.ReadLine();
        }
    }

    explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符。 例如,在下面的示例中,此运算符将名为 Fahrenheit 的类转换为名为 Celsius 的类

    class Celsius
    {
        public Celsius(float temp)
        {
            degrees = temp;
        }
        public static explicit operator Fahrenheit(Celsius c)
        {
            return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
        }
        public float Degrees
        {
            get { return degrees; }
        }
        private float degrees;
    }
    
    class Fahrenheit
    {
        public Fahrenheit(float temp)
        {
            degrees = temp;
        }
        // Must be defined inside a class called Fahrenheit:
        public static explicit operator Celsius(Fahrenheit fahr)
        {
            return new Celsius((5.0f / 9.0f) * (fahr.degrees - 32));
        }
        public float Degrees
        {
            get { return degrees; }
        }
        private float degrees;
    }
    
    class MainClass
    {
        static void Main()
        {
            Fahrenheit fahr = new Fahrenheit(100.0f);
            Console.Write("{0} Fahrenheit", fahr.Degrees);
            Celsius c = (Celsius)fahr;
    
            Console.Write(" = {0} Celsius", c.Degrees);
            Fahrenheit fahr2 = (Fahrenheit)c;
            Console.WriteLine(" = {0} Fahrenheit", fahr2.Degrees);
        }
    }
  • 相关阅读:
    4-11 EurekaClient集成演示
    4-10 原始版服务调用演示
    4-9 Consumer内容准备
    4-8 Provider内容准备
    Swift:用UICollectionView整一个瀑布流
    Swift: 用Alamofire做http请求,用ObjectMapper解析JSON
    Swift: 用UserDefaults保存复杂对象
    BAT的真的适合创业团队吗?
    为什么要用GCD-Swift2.x
    Objective-C的泛型
  • 原文地址:https://www.cnblogs.com/fej121/p/4103333.html
Copyright © 2011-2022 走看看