2014-12-05 48 views
0

我有一個字典類,我想做到以下幾點:我可以使用泛型來調用它的構造函數嗎?

export class Dictionary<K, V> { 
    private table:{ [key: string]: IDictionaryPair<K, V> }; 
    private nElements:number; 

    constructor(src:Dictionary<K, V>) { 

      for (var item in src.table) 
       if (src.hasOwnProperty(item)) { 
        windward.trap(); 
        var valCopy = new V(src[<string>item]); 
        this.setValue(<K>item, valCopy); 
       } 
    } 
} 

這一切除了工作帶來極大的「VAR valCopy =新V(SRC [項目]);」不允許。有沒有辦法做到這一點?因爲如果類型V有一個拷貝構造函數,那麼這是全部有效的,包括類型檢查。

有沒有辦法做到這一點?

謝謝 - 戴夫

+0

V是一個類型參數,而不是一個類型。除非將其轉換爲特定類型,否則無法知道構造函數的外觀。 – 2014-12-05 15:54:30

回答

1

所有類型的信息在運行時被刪除,所以你需要將爲了在運行時仍然存在於新建立一個實例的東西:

export class Dictionary<K, V> { 
    private table:{ [key: string]: IDictionaryPair<K, V> }; 
    private nElements:number; 

    constructor(src:Dictionary<K, V>, myType: any) { 

      for (var item in src.table) 
       if (src.hasOwnProperty(item)) { 
        windward.trap(); 
        var valCopy = <V> new myType(src[<string>item]); 
        this.setValue(<K>item, valCopy); 
       } 
    } 
} 

你甚至可以限制它使你能保證構造函數簽名是你所期望的:使用

export interface MyNewable<T> { 
    new(input: string) : T; 
} 

export class Dictionary<K, V> { 
    private table:{ [key: string]: IDictionaryPair<K, V> }; 
    private nElements:number; 

    constructor(src:Dictionary<K, V>, type: MyNewable<V>) { 

      for (var item in src.table) 
       if (src.hasOwnProperty(item)) { 
        windward.trap(); 
        var valCopy = <V> new type(src[<string>item]); 
        this.setValue(<K>item, valCopy); 
       } 
    } 
} 

例約束版本(由不及格的簡化)

export class MyClass { 
    constructor(input: string) { 

    } 
} 

export class Example { 
    constructor(input: number) { 

    } 
} 

var d = new Dictionary<string, MyClass>(null, MyClass); 

// Complier warning - type `Example` isn't compatible. 
var e = new Dictionary<string, MyClass>(null, Example); 
+1

哦哇 - 謝謝你! – 2014-12-05 16:15:37

相關問題