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



我在c#中发现了一些令人困惑的东西:在实现IInterface的类中定义Method()IInterface.Method()的能力。

的例子:

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. 这样做的理由是什么?我无法想象一个有效的用例,只有潜在的混乱和额外的能力,为开发人员搬起石头砸自己的脚。

想象你的类CustomerBase实现了多个接口,如ICustomer,ICustomer1....这些接口有一些通用的方法签名,在您的例子中我们说void GetName。在这种情况下,编译器将如何确定哪个方法定义是为哪个接口在你的类?

相关内容

最新更新