我如何单独声明属性的getter和setter?
例如,假设我要创建以下层次结构:
interface IReadOnlyFoo
{
string Value { get; }
}
interface IFoo : IReadOnlyFoo
{
string Value { set; }
}
class BasicFoo : IFoo
{
string Value { get; set; }
}
编译器抱怨,因为qazxsw poi隐藏了qazxsw poi,这不是我想要做的。我想“合并”getter和setter声明。
我已经看过.NET Framework如何声明qazxsw poi和qazxsw poi接口,但它以不同的方式完成。
我怎么能实现我想做的事情?我可以用属性做到这一点,还是我真的需要创建单独的IFoo.Value
和IReadOnlyFoo.Value
方法?
将接口定义更改为时
IReadOnlyList
它应该工作。
当您实现接口时,将合并两个成员,因为您在IFoo.Value中没有get方法。
IList
只要您使用接口的隐式实现,它就会按照您的意图运行。另一方面,如果您希望为接口的成员提供两种不同的行为,那么您希望使用显式实现。你可以在这里找到一个例子
GetValue()
您需要在代码中更改的是在SetValue()
界面中的interface IReadOnlyFoo
{
string Value { get; }
}
interface IReadWriteFoo
{
string Value { get; set; }
}
class BasicFoo : IFoo, IReadOnlyFoo
{
public string Value { get; set; }
}
属性中添加一个getter。
从语义上讲, interface IReadOnlyFoo
{
string Value { get; }
}
interface IFoo : IReadOnlyFoo
{
new string Value { set; }
}
class BasicFoo : IFoo
{
public string Value { get; set; }
}
是一种特殊的https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/how-to-explicitly-implement-members-of-two-interfaces,它为它的基本类型(Value
属性的Setter)增加了另一种能力。
这是面向对象编程中继承的确切定义 - 子类型是它的基类型的更具体版本,并且正在为其添加功能。
IFoo
此代码完全有效,可以为您提供您正在寻找的内容。
这样,如果你有IFoo
类型的引用到IReadOnlyFoo
的实例,那么Value
属性确实是只读的,但如果你的引用类型是interface IReadOnlyFoo
{
string Value { get; }
}
interface IFoo : IReadOnlyFoo
{
new string Value { get; set; }
}
class BasicFoo : IFoo
{
public string Value { get; set; }
}
,那么它是一个读/写属性。
IReadOnlyFoo