为什么不能同时定义隐式和显式运算符? [英] Why can't I define both implicit and explicit operators?

查看:91
本文介绍了为什么不能同时定义隐式和显式运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能像这样定义隐式和显式运算符?

Why I cannot define both implicit and explicit operators like so?

    public class C
    {
        public static implicit operator string(C c)
        {
            return "implicit";
        }

        public static explicit operator string(C c)
        {
            return "explicit";
        }
    }

尽管您可以这样做:)

    class Program
    {
        public class A
        {

        }

        public class B
        {
            public static implicit operator A(B b)
            {
                Console.WriteLine("implicit");
                return new A();
            }
        }

        public class C : B
        {
            public static explicit operator A(C c)
            {
                Console.WriteLine("explicit");
                return new A();
            }
        }

        static void Main(string[] args)
        {
            C c = new C();

            A a = c;
            A b = (A) c;
        }
    }

此打印:

implicit
explicit

推荐答案

检查此内容:如果定义显式运算符,则可以执行以下操作:

If you define an explicit operator, you will be able to do something like this:

Thing thing = (Thing)"value";

如果定义隐式运算符,您仍然可以执行上述操作,但是您也可以利用隐式转换:

If you define an implicit operator, you can still do the above, but you can also take advantage of implicit conversion:

Thing thing = "value";

简而言之,显式只允许显式转换,而隐式只允许显式和隐式...因此,您只能定义一个的原因.

In short, explicit allows only explicit conversion, while implicit allows both explicit and implicit... hence the reason why you can only define one.

这篇关于为什么不能同时定义隐式和显式运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆