【发布时间】:2014-01-27 13:50:19
【问题描述】:
作为一项智力练习,我想我会看看我可以在 TypeScript (0.9.5) 中实现一些 .Net 泛型成员有多近,我已经达到了List<T>,但不确定我能否取得进步.
(我意识到有一些解决方法,但我特别尝试使用与 .Net 库中存在的相同实现,主要是尝试了解 TypeScript 中仍然存在的限制)。
无论如何,忽略我似乎无法以任何有意义的方式重载我的构造函数的事实,在 .Net 源代码中,构造函数 List(IEnumerable<T> collection) 检查传递的 Enumerable 不为空,然后逆变转换它使用ICollection<T> c = collection as ICollection<T> 到ICollection。
在 TypeScript 中我这样做 var c: ICollection<T> = collection(集合是 IEnumerable<T>),但得到以下错误:
Cannot convert 'IEnumerable<T>' to 'ICollection<T>': Type 'IEnumerable<T>' is missing property 'Add' from type 'ICollection<T>'.
我目前的代码如下:
export module System {
export module Collections {
export interface IEnumerator {
MoveNext(): boolean;
Reset(): void;
Current(): any;
}
export interface IEnumerable {
GetEnumerator(): IEnumerator;
}
export interface ICollection extends IEnumerable {
CopyTo(array: any[], index: number): void;
Count(): number;
SyncRoot(): any;
IsSynchronized(): boolean;
}
export interface IList extends ICollection {
[index: number]: any;
Add(value: any): number;
Contains(value: any): boolean;
Clear(): void;
IsReadOnly: boolean;
IsFixedSize: boolean;
IndexOf(value: any): number;
Insert(index: number, value: any): void;
Remove(value: any): void;
RemoveAt(index: number): void;
}
export module Generic {
export interface IEnumerator<T> extends System.Collections.IEnumerator {
Current(): T;
}
export interface IEnumerable<T> extends System.Collections.IEnumerable {
GetEnumerator(): IEnumerator<T>;
}
export interface ICollection<T> extends IEnumerable<T> {
Add(item: T): void;
Clear(): void;
Contains(item: T): boolean;
CopyTo(array: T[], arrayIndex: number): void;
Remove(item: T): boolean;
Count(): number;
IsReadOnly(); boolean;
}
export interface IList<T> extends ICollection<T> {
IndexOf(item: T): number;
Insert(index: number, item: T): void;
RemoveAt(index: number): void;
[index: number]: T;
}
export interface IReadOnlyCollection<T> extends IEnumerable<T> {
Count(): number;
}
export interface IReadOnlyList<T> extends IReadOnlyCollection<T> {
[index: number]: T;
}
export class List<T> implements IList<T>, System.Collections.IList, IReadOnlyList<T> {
private _defaultCapacity: number = 4;
private _items: T[];
private _size: number;
private _version: number;
private _syncRoot: any;
constructor(collection?: IEnumerable<T>, capacity?: number) {
// NOTE: Capacity will be ignored is Collection is not null
// This is because we don't appear to be able to overload ctors in TypeScript yet!
if (collection == null) {
if (capacity == null) {
this._items = new Array<T>(0);
}
else {
this._items = new Array<T>(capacity);
}
} else {
var c: ICollection<T> = collection;
}
}
}
}
}
}
有没有其他人尝试过接口的协方差?如果有,你是怎么过的?
谢谢,
【问题讨论】:
-
可能是演员:
var c: ICollection<T> = <ICollection<T>>collection ; -
感谢 WiredPrairie,直接投射似乎是有效的!
-
Plug : @TomTregenna 我确实有一个用于 TypeScript 中常见数据结构的库:github.com/basarat/typescript-collections
-
是的,谢谢 basarat,在我开始之前,我确实看到了您的出色工作。
标签: c# javascript .net typescript