在使用界面时如何实现私有的setter?

dot*_*oob 126 c# asp.net interface getter-setter

我创建了一个带有一些属性的界面.

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

{ get; private set; }
Run Code Online (Sandbox Code Playgroud)

但是,在使用接口时不允许这样做,这样可以实现,如果是这样,怎么办?

Roh*_*ats 244

在界面中,您只能getter为您的属性定义

interface IFoo
{
    string Name { get; }
}
Run Code Online (Sandbox Code Playgroud)

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

class Foo : IFoo
{
    public string Name
    {
        get;
        private set;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @MikeCheel那是因为接口仅定义了最少的方法/访问器。直接使用对象时,您可以随意添加更多内容。尽管在将对象用作接口类型时,仅接口中定义的那些方法/访问器才可用。 (5认同)
  • 即使接口只包含一个 getter,如果 setter 是公共的,它似乎也不会抱怨。 (2认同)

Ser*_*kiy 26

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

public interface IBar
{
    int Foo { get; }    
}
Run Code Online (Sandbox Code Playgroud)

私有setter不是public api的一部分(与任何其他私有成员一样),因此您无法在界面中定义它.但是您可以自由地将任何(私有)成员添加到接口实现中.实际上,无论setter是实现为公共还是私有,或者是否有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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)