2016-07-08 59 views
1

在打字稿这是合法的代码:为什么要将基类中的受保护访问更改为派生类中的公共访问权限?

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#中是非法的,例如。然而,在公共文件中保护是不允许的。

允许将受保护的函数作为派生类中的公共函数公开的原因是什么?从C#和Java开始,我根本无法改变成员的访问级别。

回答

1

什么是允许的保护功能的基本原理在派生类中

它允许的,因为它不是不允许公开为公共职能。你只是简单地得到你写的东西(因为你没有写这个孩子变成公开的,因为这是默认的)。

更多

语言设计https://blogs.msdn.microsoft.com/ericgu/2004/01/12/minus-100-points/

去从公众对保护不打字稿,但是允许的。

有充分的理由。考虑以下内容

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! 
+0

明确的答案,谢谢。 – Sam

相关问题