【问题标题】:Generic constructors in F#F# 中的泛型构造函数
【发布时间】: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&lt;Vector3&gt;,因此数据应该是数据类型:Vector3 []

【问题讨论】:

    标签: generics constructor f#


    【解决方案1】:

    试试这个:

    type Foo<'T>(size: int, data: 'T []) =
        new(data: 'T []) =
            Foo(sizeof<'T>, data)
        member this.Size() = size
    

    请注意,在测试时您应该小心。当你调用Foo([|1,2,3,4|]) 时,它推断T 的类型是int * int * int * int。使用分号分隔数组元素:

    Foo([|1;2;3;4|]).Size()           // 4
    Foo([|1.f;2.f;3.f;4.f|]).Size()   // 4
    Foo([|1.m;2.m;3.m;4.m|]).Size()   // 16
    

    更新
    鉴于您更新的问题,您似乎正在尝试做一些部分专业化。我建议不要尝试在泛型类本身中执行此操作,毕竟,.NET 中泛型的全部意义在于您不必为要使用的每种类型制定不同的策略.相反,使用静态工厂创建一个单独的类型,以生成您的 Foo 对象,并为您想要创建的各种类型提供多个重载:

    type Foo<'T>(size: int, data: 'T []) =
        member this.Size() = size
    
    type Foo =
        static member from (data : int[]) = Foo(16, data)
        static member from (data : float[]) = Foo(4, data)
        static member from (data : Vector3[]) = Foo(Vector3.SizeInBytes, data)
        static member from (data : 'T[]) = Foo(sizeof<'T>, data)
    
    Foo.from([|1;2;3;4|]).Size()                // 16
    Foo.from([|1.f;2.f;3.f;4.f|]).Size()        // 4
    Foo.from([|Vector3(1.f,1.f,1.f)|]).Size()   // Vector3.SizeInBytes
    Foo.from([|1.m;2.m;3.m;4.m|]).Size()        // 16
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      相关资源
      最近更新 更多