如果我有一个接口:
interface IFoo
{
int Offset {get;}
}我能要这个吗:
interface IBar: IFoo
{
int Offset {set;}
}那么IBar的消费者将能够设置或获取?
发布于 2009-01-17 12:30:42
不,你不能!
(我正要写“是的”,但在阅读了安东尼的帖子,并尝试了一些调整后,我发现答案是否定的!)
class FooBar : IFoo, IBar
{
public int Offset{get;set;}
}(将生成一个警告,正如Anthony所指出的,可以通过添加"new“关键字来修复。)
在试用代码时:
IBar a = new FooBar();
a.Offset = 2;
int b = a.Offset;最后一行将生成编译错误,因为您已经隐藏了IBar的偏移设置器。
编辑:修复了类中属性的accesibillity修饰符。谢谢安东尼!
发布于 2009-01-17 12:19:58
这很接近,但不是香蕉。
interface IFoo
{
int Offset { get; }
}
interface IBar : IFoo
{
new int Offset { set; }
}
class Thing : IBar
{
public int Offset { get; set; }
}注意IBar中的new关键字,但它覆盖了IFoo的get访问器,因此IBar没有get。因此,不能在保留现有get的同时创建简单地添加set的IBar。
发布于 2009-01-17 12:37:28
+1到Arjan Einbu
当然,IBar的使用者将无法获得偏移量属性的值,因为IFoo的继承不会改变IBar编译器中定义的偏移量属性的语义,这是有原因的。当您使用“新”关键字编译器完全消除歧义,并将IBar.Offset视为只写。但是,从IBar接口继承的类的使用者将能够获取和设置Offset属性。
如果你使用显式的接口实现,这种差异会变得更加明显:
class Boo: IBar
{
int IFoo.Offset { get { return 0; } }
int IBar.Offset
{
set { } // OK - IBar has a setter
get { return 1; } // compiler error - IBar.Offset doesn't inherit setter
}
}
class Program
{
static void Main(string[] args)
{
Boo b = new Boo();
int x = ((IFoo) b).Offset; // OK - IFoo.Offset has getter
((IBar) b).Offset = 1; // OK - IBar.Offset has setter
x = ((IBar) b).Offset; // compiler error - IBar doesn't inherit
// getter from IFoo
}
}https://stackoverflow.com/questions/453218
复制相似问题