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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…