Use explicit interface implementations with a dynamic object

I am experimenting with explicit implementation of interfaces. This is necessary to break intellisense into methods that are not valid in the current context. Use / practical-applications-of-the-adaptive-interface-pattern-the-fluent-builder-context / as a reference. To prove that they will not be called, I thought I could use a dynamic keyword, because then at least my code would compile. It compiles, but does not work as expected. A dynamic variable has access to class methods, but not to explicitly implemented interface methods.

public interface IAmInterface
{
    void Explicit();
    void Implicit();
}

public class Implementation : IAmInterface
{
    void IAmInterface.Explicit()
    {
    }

    public void Implicit()
    {
    }
    public static Implementation BeginBuild()
    {
        return new Implementation();
    }
}

And here are 3 tests to prove my point

[Test]
public void TestWorksAsExpected() //Pass
{
    var o = Implementation.BeginBuild();
    o.Implicit();
}

[Test]
public void TestDoesNotWorkWithExplicitImplementation() //Fails
{
    dynamic o = Implementation.BeginBuild();
    o.Explicit();
}

[Test]
public void ButWorksForImplicitImplementation() //Pass
{
    dynamic o = Implementation.BeginBuild();
    o.Implicit();
}

- , ? , , - , TennisGame.

dynamic o = TennisGame.BeginBuild().With("Player A").Versus("Player B");
o.Versus("Player C"); //Should fail. It does, but for another reason
+3
1

, .

, . dynamic , ( .., "" ). , #, , , . .

API , ( ) #, dynamic.

: , dynamic .

, ( ).

+7

Source: https://habr.com/ru/post/1532533/


All Articles