简体   繁体   English

如何使用C Sharp界面

[英]How to use c sharp interface

I have the following interface..It has a error which i had no idea why it happened. 我有以下接口..它有一个错误,我不知道为什么会发生。 Basically for the interface part string DoorDescription { get; private set; } 基本上用于接口的部分string DoorDescription { get; private set; } string DoorDescription { get; private set; } string DoorDescription { get; private set; } has to remove the private set to make it work 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";
            }
        }
    }

Please see here 请看这里

An interface can't contain constants, fields, operators, instance constructors, destructors, or types. 接口不能包含常量,字段,运算符,实例构造函数,析构函数或类型。 Interface members are automatically public, and they can't include any access modifiers. 接口成员是自动公开的,并且不能包含任何访问修饰符。 Members also can't be static. 成员也不能是静态的。

Basically an interface is a public contract . 基本上,接口是公共合同

You can set your property as read-only and then have a private set in the class which implements it . 您可以将属性设置为只读,然后在实现该属性的类中将其设置为私有

An interface can't have any private methods. 接口不能有任何私有方法。

Just remove the setter from the interface: 只需从界面中删除设置器即可:

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

The class implementing it can still have a setter for the property, and as the setter is not defined in the interface, it can be private. 实现它的类仍然可以具有该属性的设置器,并且由于未在接口中定义该设置器,因此它可以是私有的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM