2016-12-22 48 views
1

我有一個抽象類Section將用於表示可以是有效的或無效的文檔的一部分。這些部分也可以嵌入部分。如果部分包含無效的內部部分,則該部分無效。在TypeScript中獲取從某種類型派生的類型屬性的屬性值?

我創建的類ASection1ASection2爲使用它們作爲MySection內部部分中,向其中驗證過程是通過performValidation()裝置調用的目的。

如何獲取從MySection類派生的類型的屬性。我需要關於抽象類反射邏輯的幫助,如下所述。

abstract class Section { 

    constructor(public name: string) { 
    } 

    performValidation(): boolean { 

     let result: boolean = true; 

     //HELP IS NEEDED HERE!!! 
     //get all properties of this instance 
     //whose type inherit from "Section" 
     //and execute Validate() on each of them 
     //one at a time, if any of them returns 
     //false, return false. 

     return this.Validate(); 
    } 

    abstract Validate(): boolean; 
} 

class ASection1 extends Section { 
    constructor() { 
     super("Section example 1"); 
    } 
    Validate(): boolean { 
     //validation logic goes here 
    } 
} 

class ASection2 extends Section { 
    constructor() { 
     super("Section example 2"); 
    } 
    Validate(): boolean { 
     //validation logic goes here 
    } 
} 

class MySection extends Section { 

    constructor() { 
     super("My Section"); 
    } 

    subsection1: ASection1; 
    subsection2: ASection2; 

    prop1: number; 

    Validate(): boolean { 
     return this.prop1 > 100; 
    } 

} 

//run 

let mySect = new MySection(); 
mySect.prop1 = 101; 
mySect.subsection1 = new ASection1(); 
mySect.subsection2 = new ASection2(); 
mySect.performValidation(); 

謝謝。

+1

爲什麼你不只是將部分存儲在一個Map數組中,而不是未知的單個屬性? –

回答

0

如果您有兩個或更多相同類型和相同含義的屬性每次使用array而不是每個屬性。我爲每個小節添加小節數組。在驗證中,我檢查每個小節,如果任何小節驗證失敗循環返回false,如果沒有小節驗證失敗驗證繼續通過驗證自己。

abstract class Section { 
    protected subsections: Array<Section> = []; 

    constructor(public name: string) { 
    } 

    performValidation(): boolean { 

     let result: boolean = true; 

     for (var i = 0; i < this.subsections.length; i++) { 
      if (!this.subsections[i].Validate()) { 
       return; 
      } 
     } 

     return this.Validate(); 
    } 

    public addSubsection(section: Section) { 
     this.subsections.push(section); 
    } 

    abstract Validate(): boolean; 
} 

class ASection1 extends Section { 
    constructor() { 
     super("Section example 1"); 
    } 

    Validate(): boolean { 
     //validation logic goes here 
    } 
} 

class ASection2 extends Section { 
    constructor() { 
     super("Section example 2"); 
    } 
    Validate(): boolean { 
     //validation logic goes here 
    } 
} 

class MySection extends Section { 

    constructor() { 
     super("My Section"); 
    } 

    prop1: number; 

    Validate(): boolean { 
     return this.prop1 > 100; 
    } 

} 

//run 

let mySect = new MySection(); 
mySect.prop1 = 101; 
mySect.addSubsection(new ASection1()); 
mySect.addSubsection(new ASection2()); 
mySect.performValidation();