【发布时间】:2011-09-07 13:31:14
【问题描述】:
我正在将一些 Java 代码移植到 C#,我遇到了这个用于复制对象的习惯用法:
class Base
{
int x;
public Base(int x) { this.x = x; }
protected Base(Base other) { x = other.x; }
}
class Derived : Base
{
Base foo;
public Derived(Derived other)
: base(other)
{
foo = new Base(other.foo); // Error CS1540
}
}
错误 CS1540 是:
无法通过“Base”类型的限定符访问受保护的成员“Base.Base(Base)”;限定符必须是“派生”类型(或派生自它)
我了解此错误的目的:它阻止访问同级类型的受保护成员。但是 Base.Base(Base) 显然不会在兄弟类型上调用!这只是没有包含在规范中,还是我错过了一些不安全的原因?
编辑:啊,成语是new Base(other.foo) 而不是new Base(other)
【问题讨论】:
-
@Alastair Pitts -- 是的......你是对的
标签: c# inheritance constructor protected