考虑以下类和接口:
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# 不能解决这个问题?从架构的角度来看,我正在做的事情是不是很疯狂?我试图了解原因(我知道可以通过强制转换来解决)。
编辑
当我介绍 interface 时出现了问题C
。当我使用时MyClass : A, B
,我完全没有问题。
最终的
刚刚完成了一个关于这个主题的博客:接口歧义和隐式实现。