允许实现 IInterface 的 IInterface.Method() 和 Method() 的基本原理是什么?

What is the rationale of allowing IInterface.Method() and Method() that implements IInterface?

我在 C# 中确实发现了一些令人困惑的东西:在实现 class 中定义 Method() IInterface.Method() 的能力16=].

示例:

public interface ICustomer
{
    void GetName();
}

public class CustomerBase : ICustomer
{
    public void GetName()
    {
        Console.WriteLine("CustomerBase");
    }

    void ICustomer.GetName()
    {
        Console.WriteLine("ICustomer.CustomerBase.GetName()");
    }
}

是的,GetName()ICustomer的一种契约方式,可以与ICustomer.GetName()共存。

什么时候调用哪个方法?我 运行 控制台中的东西:

    var customerBase = new CustomerBase();
    customerBase.GetName();  //this prints CustomerBase
    ((ICustomer)customerBase).GetName(); //this prints ICustomer.CustomerBase.GetName()

因此,根据是否将 customerBase 转换为接口,输出会有所不同。

不仅如此,方法签名现在会影响正在调用的方法:

    private void PrintCustomer(ICustomer customer)
    {
        customer.GetName();  //this prints ICustomer.CustomerBase.GetName()
    }

    private void PrintCustomer(CustomerBase customer)
    {
        customer.GetName(); //this prints CustomerBase
    }

这种行为对我来说非常违反直觉。那么这里有语言律师的问题:

  1. 何时在 C# 规范中引入它,在何处引入?
  2. 这样做的理由是什么?我无法想象一个有效的用例,只有潜在的混乱和额外的能力让开发人员搬起石头砸自己的脚。

所以想象一下您的 class CustomerBase 已经实现了多个接口,例如 ICustomerICustomer1…。这些接口有一些通用的方法签名,假设你的情况是void GetName。在那种情况下,编译器将如何确定哪个方法定义适用于您的 class?

中的哪个接口