C# 使用接口时如何实现私有 setter?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18249981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:40:10  来源:igfitidea点击:

How do you implement a private setter when using an interface?

c#asp.netinterfacegetter-setter

提问by dotnetnoob

I've created an interface with some properties.

我创建了一个具有一些属性的界面。

If the interface didn't exist all properties of the class object would be set to

如果接口不存在,类对象的所有属性都将设置为

{ get; private set; }

However, this isn't allowed when using an interface,so can this be achieved and if so how?

但是,这在使用接口时是不允许的,所以可以实现吗?如果可以,如何实现?

采纳答案by Rohit Vats

In interface you can define only getterfor your property

在界面中,您只能getter为您的财产定义

interface IFoo
{
    string Name { get; }
}

However, in your class you can extend it to have a private setter-

但是,在您的课程中,您可以将其扩展为private setter-

class Foo : IFoo
{
    public string Name
    {
        get;
        private set;
    }
}

回答by Sergey Berezovskiy

Interface defines public API. If public API contains only getter, then you define only getter in interface:

接口定义了公共 API。如果公共 API 只包含 getter,那么您只在接口中定义 getter:

public interface IBar
{
    int Foo { get; }    
}

Private setter is not part of public api (as any other private member), thus you cannot define it in interface. But you are free to add any (private) members to interface implementation. Actually it does not matter whether setter will be implemented as public or private, or if there will be setter:

私有 setter 不是公共 api 的一部分(与任何其他私有成员一样),因此您不能在接口中定义它。但是您可以自由地向接口实现添加任何(私有)成员。实际上,无论 setter 将被实现为 public 还是 private ,或者是否有 setter 都没有关系:

 public int Foo { get; set; } // public

 public int Foo { get; private set; } // private

 public int Foo 
 {
    get { return _foo; } // no setter
 }

 public void Poop(); // this member also not part of interface

Setter is not part of interface, so it cannot be called via your interface:

Setter 不是接口的一部分,因此不能通过您的接口调用它:

 IBar bar = new Bar();
 bar.Foo = 42; // will not work thus setter is not defined in interface
 bar.Poop(); // will not work thus Poop is not defined in interface