作为一个智力练习,我想我会看到我可以在TypeScript(0.9.5)中实现一些.Net泛型成员的密切程度,但我得到的结果高达List<T>
,但不确定我可以进步。 (我知道有这种解决方法,但我特别试图使用与.Net库中存在的相同的实现,主要是尝试了解TypeScript中仍然存在的限制)。TypeScript中的界面逆转因子
无论如何,忽略这样一个事实,即我似乎无法以任何有意义的方式重载我的构造函数,在.Net源构造函数List(IEnumerable<T> collection)
检查传递的Enumerable不为null,然后将其转换为ICollection使用ICollection<T> c = collection as ICollection<T>
。
在打字稿我这样做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;
}
}
}
}
}
}
有任何人试图CO /禁忌变化,其接口?如果是这样,你是怎么做的?
感谢,
也许演员:'var c:ICollection = >集合;' –
WiredPrairie
感谢WiredPrairie,做直接演员似乎是有效的! –
插件:@TomTregenna我在TypeScript中有一个用于常见数据结构的库:https://github.com/basarat/typescript-collections – basarat