我需要创建一个安全的构造函数,它只在值正确时才构建对象,所以我想在构造函数中返回 null(而不是创建对象的实例)如何做到这一点?
在我的班级 Aresta 中,从构造函数返回 null 不起作用;
export class Aresta{
private feromonioAtual : number;
private distancia : number;
private noFim: No;
constructor(noFim:No, distancia:number){
if(distancia<=0){
//null return isn't work :(
return null;
}
this.feromonioAtual = 1;
this.noFim = noFim;
this.distancia = distancia;
}
}
这种验证是在工厂的类之外处理的。
export class Aresta {
private feromonioAtual: number;
private distancia: number;
private noFim: number;
constructor(noFim: number, distancia: number) {
this.feromonioAtual = 1;
this.noFim = noFim;
this.distancia = distancia;
}
}
export class ArestaFactory {
public static buildAresta(noFim: number, distancia: number): Aresta {
if (distancia <= 0) {
return null; // or throw an exception
}
return new Aresta(noFim, distancia);
}
}
遗憾的是到现在为止是打字稿没有包/模块私有访问,但关于它的票是在他们的GitHub开在这里。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句