【发布时间】:2011-07-29 21:54:21
【问题描述】:
考虑以下类和接口:
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; }
}
看起来很简单,对吧?现在考虑以下程序:
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();
}
看起来不错,但它不会编译。它给了我一个歧义异常:
为什么 C# 不能解决这个问题?从架构的角度来看,我正在做的事情是不是很疯狂?我正在尝试理解为什么(我知道可以通过强制转换来解决)。
编辑
当我引入接口C时出现问题。当我使用MyClass : A, B 时,我一点问题都没有。
最终
刚刚完成了一篇关于该主题的博客:Interface Ambiguity and Implicit Implementation。
【问题讨论】:
-
您期望它会调用哪个?
-
这只是你在搞砸的东西,还是你设计的一部分?
-
@Nix 好吧...我们有一些接口存在这个问题。 A 和 B 是非常小的接口,而 C 在一个需要继承 A 和 B 的大接口中。
-
如果接口A和B有相同的方法,为什么不从包含这些方法的接口继承呢?这将解决您的问题。
-
一个更有趣的问题是,为什么即使 A 的属性是只读的而 B 的属性是只写的,您的代码也无法工作。看起来有一个只读属性和一个只写属性不应该使读取或写入模棱两可,但编译器会抱怨模棱两可。
标签: c# .net inheritance interface ambiguity