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)
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)
归档时间: |
|
查看次数: |
29268 次 |
最近记录: |