【问题标题】:Interface property fails when defining explicitly显式定义时接口属性失败
【发布时间】:2012-06-29 03:51:09
【问题描述】:

我正在学习接口属性,并遇到了一些我认为应该基于 MSDN 和书籍示例工作的东西,但事实并非如此。如果我显式实现接口属性,则当我的类实例尝试访问时它不会被识别,但如果我隐式执行它则可以正常工作(不确定这是否是正确的术语)。

interface IMyInterface
  {
    string Name { get; set; }       
  }

class MyClass : IMyInterface
{
    private string name;

    string IMyInterface.Name  //works if not explicit: i.e., public string Name
    {
        get { return this.name; }
        set { this.name = value; }
    }
}


class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();
        myClass.Name = "blah";  // fails

    }
}

【问题讨论】:

    标签: c# properties explicit-interface


    【解决方案1】:

    这就是它应该如何与explicit interface implementations一起工作:

    实现接口的类可以显式实现该接口的成员。当成员显式实现时,不能通过类实例访问,只能通过接口实例访问。

    因此,如果您像这样重新编写代码,它应该不再失败:

    static void Main(string[] args)
    {
        IMyInterface myClass = new MyClass();
        myClass.Name = "blah";  // no longer fails
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2013-06-20
      • 2016-09-05
      • 1970-01-01
      • 2011-11-07
      相关资源
      最近更新 更多