Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm experimenting with explicit implentations of interfaces. This is to strip the intellisense with methods which are not valid in the current context. Use /practical-applications-of-the-adaptive-interface-pattern-the-fluent-builder-context/ as reference. To prove that they would not be callable, I thought I could use the dynamic keyword, because then at least my code would compile. It does compile, but it does not work as expected. The dynamic variable has access to the class methods, but not the interface methods that are explicit implemented.

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 the 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();
}

Would anyone be kind enough to explain the reason for this? One example where I wanted this functionality was to prove that I couldnt add more than two players in a TennisGame.

dynamic o = TennisGame.BeginBuild().With("Player A").Versus("Player B");
o.Versus("Player C"); //Should fail. It does, but for another reason
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
377 views
Welcome To Ask or Share your Answers For Others

1 Answer

The dynamic variable has access to the class methods, but not the interface methods that are explicit implemented.

Yes, that is correct. dynamic has access to the regular members that would be accessible (based on context etc, usually means "public"). However, the only way, even in regular C#, to invoke explicit interface implementations, is to cast the object to the interface. This remains the case with dynamic.

Implicit interfact implementations are also part of the regular class API, so they are externally available (against the type) to both regular c# and dynamic.

Basically: no, dynamic can not and will not access explicit interface implementations.

Either cast to the interface, or use reflection from the interface type (not the object type).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...