Why can't I define both implicit and explicit operators?

后端 未结 2 441
旧巷少年郎
旧巷少年郎 2020-12-29 03:19

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

    public class C
    {
        public static implicit operator string(C c)
        {
             


        
相关标签:
2条回答
  • 2020-12-29 03:24

    Check this: Why can't coexist implicit and explicit operator of the same type in C#?

    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.

    0 讨论(0)
  • 2020-12-29 03:36

    I don't know the technical limitation that prevents this, but I think they would have done this to prevent people from shooting their own feet off.

    string imp = new C(); // = "implicit"
    string exp = (string)new C(); // = "explicit"
    

    That would drive me bonkers and makes no sense, C should only cast to a string 1 way, not 2 different ways.

    0 讨论(0)
提交回复
热议问题