【发布时间】:2014-01-04 20:44:34
【问题描述】:
我正在使用 OpenTK 及其数学库,但不幸的是矢量类没有通用接口。例如 Vector2 ,3 和 4 都有相同的静态方法 SizeInBytes http://www.opentk.com/files/doc/struct_open_t_k_1_1_vector3.html#ae7cbee02af524095ee72226d842c6892
现在我可以重载大量不同的构造函数,但我认为应该可以通过类型约束来解决这个问题。
我正在阅读 http://msdn.microsoft.com/en-us/library/dd233203.aspx 并找到了这个
type Class4<'T when 'T : (static member staticMethod1 : unit -> 'T) > =
class end
现在我已经自己尝试过了,但我无法正确使用语法。
type Foo<'T when 'T: (static member SizeInBytes: unit -> int)>(data: 'T []) =
member this.GetBytes() = 'T.SizeInBytes()
let f = Foo([|new Vector3(1.0f,1.0f,1.0f)|])
f.GetBytes()
你能发现问题吗?
编辑:
VS2012 抱怨这条线 'T.SizeInBytes() //Unexpected symbol or expression 和 T.SizeInBytes() 也不起作用。
编辑2:
我做了一个不涉及外部库的例子
type Bar() =
static member Print() = printf "Hello Foo"
type Foo<'T when 'T: (static member Print: unit -> unit)>(data: 'T []) =
member this.Print() = 'T.Print()
let b1 = Bar()
let f = Foo([|b1|])
f.Print()
【问题讨论】:
-
您能详细说明问题所在吗?
-
@GaneshSittampalam 我添加了错误消息。
标签: f#