【问题标题】:How to declare private abstract method in TypeScript?如何在 TypeScript 中声明私有抽象方法?
【发布时间】:2017-04-17 07:44:48
【问题描述】:

如何在 TypeScript 中正确定义私有抽象方法?

这是一个简单的代码:

abstract class Fruit {
    name: string;
    constructor (name: string) {
        this.name = name
    }
    abstract private hiFrase (): string;
}

class Apple extends Fruit {
    isCitrus: boolean;
    constructor(name: string, isCitrus: boolean) {
        super(name);
        this.isCitrus = isCitrus;
    }

    private hiFrase(): string {
        return "Hi! I\'m an aplle and my name is " + this.name + " and I'm " + (isCitrus ? "" : " not ") + "citrus";
    }

    public sayHi() {
        alert(this.hiFrase())
    }
}

此代码不起作用。如何解决?

【问题讨论】:

  • private == 只能在同一个类中访问。 abstract == 未在此类中实现,而是在某些继承类中实现。这里有定义冲突。
  • 你想要protected abstract,而不是private abstract
  • +deceze,是不是意味着我必须在每个派生类中定义hiFrase()方法(PearOrange等)?
  • +series0ne,我希望它是一个私有方法,但如果我不能保护也是可以接受的决定。谢谢

标签: javascript typescript


【解决方案1】:

别说,isCitrus 应该是 this.isCitrus。继续主节目...

抽象方法必须对子类可见,因为您需要子类来实现该方法。

abstract class Fruit {
    name: string;
    constructor (name: string) {
        this.name = name
    }
    protected abstract hiFrase(): string;
}

class Apple extends Fruit {
    isCitrus: boolean;
    constructor(name: string, isCitrus: boolean) {
        super(name);
        this.isCitrus = isCitrus;
    }

    protected hiFrase(): string {
        return "Hi! I\'m an aplle and my name is " + this.name + " and I'm " + (this.isCitrus ? "" : " not ") + "citrus";
    }

    public sayHi() {
        alert(this.hiFrase())
    }
}

如果您希望该方法真正私有,请不要在基类中声明它。

abstract class Fruit {
    name: string;
    constructor (name: string) {
        this.name = name
    }
}

class Apple extends Fruit {
    isCitrus: boolean;
    constructor(name: string, isCitrus: boolean) {
        super(name);
        this.isCitrus = isCitrus;
    }

    private hiFrase(): string {
        return "Hi! I\'m an aplle and my name is " + this.name + " and I'm " + (this.isCitrus ? "" : " not ") + "citrus";
    }

    public sayHi() {
        alert(this.hiFrase())
    }
}

【讨论】:

  • 那我们如何强制子类遵循相同的方法来实现呢?
  • 基类上的方法不能既是抽象的又是私有的——这是没有意义的,因为如果你想让它在子类中实现,它怎么可能是“抽象类的私有”?它必须至少在抽象类中受到保护。
  • 用例是你想强制子类实现相同的私有函数。该抽象方法将保持私有,但定义将来自抽象类。
  • 为什么应该是this.isCitrus? @芬顿
  • @SLLegendre 因为在 private hiFrase(): string 方法内部,您必须在成员名称前面加上 this. - 否则会出现编译器错误。
猜你喜欢
  • 2012-10-31
  • 2011-02-21
  • 2016-05-10
  • 2011-01-23
  • 2020-05-12
  • 1970-01-01
  • 2011-07-18
  • 1970-01-01
相关资源
最近更新 更多