explicit and implicit c#

前端 未结 7 1942
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 13:31

I\'m new to C# and learning new words. I find it difficult to understand what\'s the meaning of these two words when it comes to programming c#. I looked in the dictionary

相关标签:
7条回答
  • 2020-12-07 13:57

    Consider you have two classes:

    internal class Explicit
    {
        public static explicit operator int (Explicit a)
        {
            return 5;
        }
    }
    
    
    internal class Implicit
    {
        public static implicit operator int(Implicit a)
        {
            return 5;
        }
    }
    

    and two objects:

    var obj1 = new Explicit();
    var obj2 = new Implicit();
    

    you can now write:

    int integer = obj2; // implicit conversion - you don't have to use (int)
    

    or:

    int integer = (int)obj1; // explicit conversion
    

    but:

    int integer = obj1; // WON'T WORK - explicit cast required
    

    Implicit conversion is meant to be used when conversion doesn't loose any precision. Explicit conversion means, that you can loose some precision and must state clearly that you know what you're doing.

    There is also a second context in which implicit/explicit terms are applied - interface implementation. There are no keywords in that case.

    internal interface ITest
    {
        void Foo();
    }
    
    class Implicit : ITest
    {
        public void Foo()
        {
            throw new NotImplementedException();
        }
    }
    
    class Explicit : ITest
    {
        void ITest.Foo() // note there's no public keyword!
        {
            throw new NotImplementedException();
        }
    }
    
    Implicit imp = new Implicit();
    imp.Foo();
    Explicit exp = new Explicit();
    // exp.Foo(); // won't work - Foo is not visible
    ITest interf = exp;
    interf.Foo(); // will work
    

    So when you use explicit interface implementation, interface's methods are not visible when you use concrete type. This can be used when interface is a helper interface, not part of class'es primary responsibility and you don't want additional methods to mislead someone using your code.

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