Kee*_*ker 7 .net c# inheritance interface ambiguity
考虑以下类和接口:
public interface A { string Property { get; set; } }
public interface B { string Property { get; set; } }
public interface C : A, B { }
public class MyClass : C
{
public string Property { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
看起来很简单吧?现在考虑以下程序:
static void Main(string[] args)
{
MyClass myClass = new MyClass();
myClass.Property = "Test";
A aTest = myClass;
B bTest = myClass;
C cTest = myClass;
aTest.Property = "aTest";
System.Console.WriteLine(aTest.Property);
bTest.Property = "bTest";
System.Console.WriteLine(bTest.Property);
cTest.Property = "cTest";
System.Console.WriteLine(cTest.Property);
System.Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)
看起来没问题,但它不会编译.它给了我一个歧义异常:

为什么C#不能解决这个问题?从架构的角度来看,我在疯狂吗?我试图理解为什么(我知道它可以通过铸造来解决).
编辑
当我介绍界面时出现了问题C.当我使用时,MyClass : A, B我根本没有任何问题.
最后
刚刚完成了一个关于这个主题的博客:界面歧义和隐式实现.
简而言之,因为它确实很模糊.
现在更详细的故事.正如您已经看到的那样,有明确的接口实现,因此您可以为A.Property和B.Property提供两种不同的实现,当您只有C时,您无法判断实现是否相同.由于C#"哲学"不是猜测你的意思,而是让你在必要时更清楚地表明它,编译器不会选择A.Property或B.Property,但报告错误.
| 归档时间: |
|
| 查看次数: |
1793 次 |
| 最近记录: |