Ken*_*art 5 .net c# abstract-class interface
为什么以下是合法的C#:
public interface ISomeInterface
{
int SomeProperty
{
get;
}
}
public class SomeClassImplementingInterface : ISomeInterface
{
public int SomeProperty
{
get { return 32; }
protected set {}
}
}
Run Code Online (Sandbox Code Playgroud)
但这不是:
public abstract class SomeAbstractClass
{
public abstract int SomeProperty
{
get;
}
}
public class SomeClassExtendingAbstractClass : SomeAbstractClass
{
public override int SomeProperty
{
get { return 32; }
protected set {}
}
}
Run Code Online (Sandbox Code Playgroud)
后者导致以下编译时错误:
'InterfaceAbstractTest.SomeClassExtendingAbstractClass.SomeProperty.set':无法覆盖,因为'InterfaceAbstractTest.SomeAbstractClass.SomeProperty'没有可覆盖的set访问器InterfaceAbstractTest
在允许前者的同时不解除后者的原因是什么?
因为使用接口的调用者只关心接口的实现者至少实现接口的定义,如 @davisoa 所示,而SomeAbstractClass在您的示例中定义了一个公共契约,其中准确说明了类型、可访问性和(对于属性)可读性/可写性的成员。
SomeProperty如果您使用反射来获取(从基类或子类)的 PropertyInfo ,则它需要从某个地方解析该信息。允许子类更改可读性/可写性与更改返回类型或参数列表一样违反合同。
想象一下例如:
SomeAbstractClass sc = new SomeClassExtendingAbstractClass();
PropertyInfo pi = sc.GetType().GetProperty("SomeProperty");
Console.Out.WriteLine(pi.CanWrite); // What should be printed here?
Run Code Online (Sandbox Code Playgroud)