在TypeScript中,这是合法代码:
class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}
protected move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) {
super(name);
}
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
class Horse extends Animal {
constructor(name: string) {
super(name);
}
move(distanceInMeters = 45) {
console.log("Galloping...");
super.move(distanceInMeters);
}
}
但是,例如,这在C#中是非法的。但是,在TypeScript中不允许从public访问受保护。
允许受保护函数作为派生类中的公共函数公开的基本原理是什么?来自C#和Java,根本不允许更改成员的访问级别。
答案 0 :(得分:1)
允许受保护函数作为派生类中的公共函数公开
的基本原理是什么
这是允许的,因为它不被禁止。你只是得到你写的东西(因为你没有把孩子写成公开,因为那是默认的)。
语言设计https://blogs.msdn.microsoft.com/ericgu/2004/01/12/minus-100-points/
然而,在TypeScript中不允许从公共到受保护。
有充分的理由。请考虑以下
class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) {
super(name);
}
protected move(distanceInMeters = 5) { // If allowed
console.log("Slithering...");
super.move(distanceInMeters);
}
}
let snake = new Snake('slitherin');
snake.move(); // ERROR
let foo: Animal = snake;
foo.move(); // HAHA made my way around the error!