【问题标题】:In Typescript, is there any way to write a class as a Array, so I can do class[i], like a List<T> in C#在 Typescript 中,有没有办法将一个类写成一个数组,所以我可以做 class[i],就像 C# 中的 List<T>
【发布时间】:2019-01-16 09:58:12
【问题描述】:

我是一个从 C# 开始的新游戏开发者。

现在我需要将我的一个游戏转移到 typescript。

我尝试在 typescript 中自定义一个列表,这是我在 C# 中非常熟悉的。 我的代码如下:

export class List {

private items: Array;
constructor() {
    this.items = [];
}

get count(): number {
    return this.items.length;
}

add(value: T): void {
    this.items.push(value);
}

get(index: number): T {
    return this.items[index];
}
contains(item: T): boolean{
    if(this.items.indexOf(item) != -1){
        return true;
    }else{
        return false;
    }
}
clear(){
    this.items = [];
}
}

不过,我想制作一个数组,这样我就可以执行以下操作:

someList[i] = this.items[i];

我猜这类似于运算符重载,但我不太确定。
谁能告诉我怎么做?
提前致谢。

【问题讨论】:

    标签: javascript typescript overloading operator-keyword


    【解决方案1】:

    简单地扩展数组

    export class List<T> extends Array<T> {
    
        constructor() {
            super();
        }
    
        get count(): number {
            return this.length;
        }
    
        add(value: T): void {
            this.push(value);
        }
    
        get(index: number): T {
            return this[index];
        }
    
        contains(item: T): boolean {
            if (this.indexOf(item) != -1) {
                return true;
            } else {
                return false;
            }
        }
    
        clear() {
            this.splice(0, this.count);
        }
    }
    

    【讨论】:

    • 感谢快速回复,可以了,除了clear()方法,不能这样= [];
    • 我很确定您不再需要 private items: Array&lt;T&gt; 字段,因为它由 Array&lt;T&gt; 处理
    • 但是当我像这样运行代码进行测试时:let testList = new List&lt;number&gt;();testList.add(1); 它记录错误:TypeError: testList.add is not a function
    • 我已经测试并编译为 ES6 像这样tsc -target ES6
    【解决方案2】:

    要达到重载索引运算符的效果,你必须use a proxy to get the runtime behavior,然后使用索引签名进行打字,像这样:

    interface List<T> {
        [n: number]: T;
    }
    

    但是代理是严肃的机器。使用方法调用的样板文件可能会更好。

    【讨论】:

    • 谢谢!认为你是对的,最好习惯使用数组
    • 这样我们就可以实现 IList 接口了,很好,Matt
    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多