为什么接口A会从接口B隐藏属性

时间:2017-06-30 09:59:28

标签: c# interface get set

请参阅下面的代码。 Visual Studio 2017告诉我IGetSet.Value隐藏属性IGet.Value,如果是这样的话,我应该添加new关键字。我理解隐藏关于类的属性的概念,但是当谈到接口时,我没有看到消息的重点。我是否添加new关键字的行为当然不同。

我想要这两个接口的堆叠,因为我希望实现读写接口的对象可以在只允许获取值的方法中使用。

现在我的问题是:

  1. 这是实现我想要的方式吗?我看到了隐藏'属性作为一种信号说“你正在做一些你可能不想做的事情,尝试以不同方式解决问题”。
  2. 一个界面如何隐藏另一个界面的属性?它不依赖于接口的实现吗?那消息为什么呢?

    public interface IGetSet : IGet
    {
        new string Value { get; set; }
    }
    
    public interface IGet
    {
        string Value { get; }
    }
    
    public class Tester : IGetSet
    {
        public string Value { get; set; }
    }
    
    [Test]
    public void InterfaceTest()
    {
        IGetSet tester = new Tester();
        tester.Value = "My Value";
        IGet getteronly = tester;
        var value = getteronly.Value;
    }
    
  3. 如果我尝试用下面的代码解决它,我会得到这个编译错误' CS0229在IGet.Value'之间存在歧义。和'ISet.Value''

    public interface ISet
    {
        string Value { set; }
    }
    
    public interface IGet
    {
        string Value { get; }
    }
    
    public interface IGetSet : IGet, ISet
    {
    
    }
    

2 个答案:

答案 0 :(得分:3)

  

这是实现我想要的方式吗?

  

我看到了隐藏'属性作为一种信号说“你正在做一些你可能不想做的事情,尝试以不同的方式解决问题”。

不,这意味着您必须评估这是否是故意的。 你是否真的打算创建第二个属性的定义,否定了第一个属性?是的,你在这种情况下做,但有时你不会。所以这就是为什么有一个警告要求你明确告诉你想要什么。

作为旁注,当您使用显式接口实现时,实际上最终可能会得到两个属性的不同实现:

public class Tester : IGetSet
{
    string IGet.Value { get { return "A"; } }

    string IGetSet.Value { get { return "B"; } set { } }
}

看到警告有一个问题吗?

答案 1 :(得分:0)

如果两个接口都具有相同的属性,则必须明确地实现它们

public interface ISet
{
    string Value { set; }
}

public interface IGet
{
    string Value { get; }
}

public class GetSetClass : IGet, ISet
{
    public string Value { get; set; }
    string IGet.Value // Explicitly implementation
    {
        get { return Value; }
    }

    string ISet.Value // Explicitly implementation
    {
        set { Value = value; }
    }
}