微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么.Net/C#不能理解与同名属性的接口继承?

考虑以下类和接口:
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.

解决方法

简而言之,因为它确实很模糊.

现在更详细的故事.正如您已经看到的那样,有明确的接口实现,因此您可以为A.Property和B.Property提供两种不同的实现,当您只有C时,您无法判断实现是否相同.由于C#“哲学”不是猜测你的意思,而是让你在必要时更清楚地表明它,编译器不会选择A.Property或B.Property,但报告错误.

原文地址:https://www.jb51.cc/csharp/98998.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐