【问题标题】:Use explicit interface implementations with a dynamic object对动态对象使用显式接口实现
【发布时间】:2012-07-22 11:32:18
【问题描述】:

我正在尝试接口的显式实现。这是用在当前上下文中无效的方法来剥离智能感知。 使用/practical-applications-of-the-adaptive-interface-pattern-the-fluent-builder-context/ 作为参考。为了证明它们是不可调用的,我想我可以使用 dynamic 关键字,因为这样至少我的代码可以编译。它可以编译,但不能按预期工作。动态变量可以访问类方法,但不能访问显式实现的接口方法。

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

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

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

这里有 3 个测试来证明我的观点

[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

【问题讨论】:

  • 你写了To prove that they would not be callable...你已经证明如果你的测试失败了。
  • 我想我没有。以网球为例;如果我将两个 Versus 放在不同的行上,则应该允许第一个,但是当使用动态时,它会失败。 RuntimeBinderException

标签: c# dynamic explicit-implementation


【解决方案1】:

动态变量可以访问类方法,但不能访问显式实现的接口方法。

是的,没错。 dynamic 可以访问可以访问的常规成员(基于上下文等,通常表示“公共”)。然而,唯一方式,即使在常规 C# 中,调用显式接口实现,是将对象强制转换为接口。动态也是如此。

隐式交互实现也是常规类 API 的一部分,因此它们对于常规 c# 和 dynamic 都是外部可用的(针对类型)。

基本上:不,dynamic 不能也不会访问显式接口实现。

要么转换到接口,要么使用接口类型的反射(不是对象类型)。

【讨论】:

  • 谢谢!我想反射是唯一可行的选择,但这似乎又有点矫枉过正。
  • 在我的情况下,我不能将它转换为接口,因为它是一个通用接口并且 IInterface 也不起作用。我也不想使用反射。有什么建议吗?
猜你喜欢
  • 2011-03-30
  • 1970-01-01
  • 2015-07-03
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-07
  • 2019-02-16
相关资源
最近更新 更多