Sim*_*han 9 c# inheritance constructor protected
我正在将一些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
}
}
Run Code Online (Sandbox Code Playgroud)
错误CS1540是:
无法通过类型为"Base"的限定符访问受保护成员'Base.Base(Base)'; 限定符必须是'Derived'类型(或从中派生)
我理解这个错误的目的:它阻止访问兄弟类型的受保护成员.但Base.Base(Base)显然不会在兄弟类型上调用!这根本没有包含在规范中,或者我错过了为什么这不安全的原因?
编辑:嘎,成语new Base(other.foo)
不是new Base(other)