加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:35:34 所属栏目:百科 来源:网络整理
导读:考虑以下类和接口: 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; } } 看起来很简单吧?现
考虑以下类和接口:
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,但报告错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读