【问题标题】:How to use c sharp interface如何使用cSharp界面
【发布时间】:2014-08-26 20:08:20
【问题描述】:

我有以下界面..它有一个错误,我不知道为什么会发生。基本上对于接口部分string DoorDescription { get; private set; } 必须删除private set 才能使其工作

namespace test6
    {
        interface IHasExteriorDoor
        {
            string DoorDescription { get; private set; }
            string DoorLocation { get; set; }
        }
        class Room : IHasExteriorDoor
        {
            public Room(string disc, string loc)
            {
                DoorDescription = disc;
                DoorLocation = loc;
            }
            public string DoorDescription { get; private set; }
            public string DoorLocation { get; set; }
        }
        class Program
        {
            static void Main(string[] args)
            {
                Room a = new Room("A","B");
                a.DoorLocation = "alien";
                //a.DoorDescription = "mars";
            }
        }
    }

【问题讨论】:

  • @MitchWheat 我的问题是接口部分和类部分都使用get;private set; 为什么它不起作用..

标签: c#


【解决方案1】:

请看here

接口不能包含常量、字段、运算符、实例 构造函数、析构函数或类型。接口成员是 自动公开,并且它们不能包含任何访问修饰符。 成员也不能是静态的。

基本上一个接口是public contract

您可以将您的属性设置为只读,然后拥有a private set in the class which implements it

【讨论】:

    【解决方案2】:

    接口不能有任何私有方法。

    只需从界面中删除setter:

        interface IHasExteriorDoor
        {
            string DoorDescription { get; }
            string DoorLocation { get; set; }
        }
    

    实现它的类仍然可以有一个属性的setter,并且由于setter没有在接口中定义,它可以是私有的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多