【发布时间】:2014-01-07 02:03:09
【问题描述】:
type Foo(size: int,data: 'T []) =
new(data: float []) =
Foo(sizeof<float>,data)
new(data: int []) =
Foo(sizeof<int>,data) //error: f# thinks that data is float []
member this.Size() = size
基本上我需要几个带有通用数组 'T [] 的构造函数,我只关心 'T 的大小。
我想这样使用它:
Foo([|1,2,3,4|]).Size() // prints size of int
Foo([|1.f,2.f,3.f,4.f|]).Size() // prints size of float
我该怎么做?
更新1:
我刚刚意识到我不能让编译器推断大小,我必须手动执行此操作。
type Foo<'T>(size: int,data: 'T []) =
new(data: float []) =
Foo(4,data)
new(data: int []) =
Foo(16,data)
new(data: Vector3 []) =
Foo(Vector3.SizeInBytes,data)
member this.Size() = size
这可能吗?
当我这样做时
Foo([|new Vector3(1.f,1.f,1.f)|] 我希望 Foo 属于 Foo<Vector3>,因此数据应该是数据类型:Vector3 []
【问题讨论】:
标签: generics constructor f#