【问题标题】:“Decorate” several types with same static member function and attribute用相同的静态成员函数和属性“装饰”几种类型
【发布时间】:2019-10-09 12:07:09
【问题描述】:

我有一个可区分联合类型的列表,例如

type Name = Name of string | NoName
type Coordinate = Coordinate of float * float | NoCoordinate
…

并且都需要相同的静态成员函数和相同的属性。例如

[<KnownType("GetKnownTypes")>]
type Name = Name of string | NoName with
    static member GetKnownTypes() =
            typedefof<Name>.GetNestedTypes(BindingFlags.Public ||| BindingFlags.NonPublic) 
            |> Array.filter FSharpType.IsUnion

我如何“装饰”该列表的每种类型,而不必将静态成员 GetKnownTypes() 添加到每种类型,以避免代码重复。也许是一个带有接口或继承的解决方案。

基本上我需要更好的编程风格的代码:

[<KnownType("GetKnownTypes")>]
type Name = Name of string | NoName with
    static member GetKnownTypes() =
            typedefof<Name>.GetNestedTypes(BindingFlags.Public ||| BindingFlags.NonPublic) 
            |> Array.filter FSharpType.IsUnion

[<KnownType("GetKnownTypes")>]
type Coordinate = Coordinate of float * float | NoCoordinate with
    static member GetKnownTypes() =
            typedefof<Coordinate>.GetNestedTypes(BindingFlags.Public ||| BindingFlags.NonPublic) 
            |> Array.filter FSharpType.IsUnion

谢谢

【问题讨论】:

  • 第一个代码 sn-p 让我觉得你缺少 Option&lt;&gt; 类型功能
  • 另外,我想知道您是否只需要为这两种类型限制GetKnownTypes。因为它看起来很容易被通用化。
  • 我需要两种以上的GetKnownTypes。我怎样才能使它通用?

标签: f#


【解决方案1】:

这似乎有点矫枉过正,但你的意思是这种事情吗?

type IReflective = 
    abstract GetKnownTypes : unit -> Type[]

let getKnownTypes<'T>() = 
    typedefof<'T>.GetNestedTypes(BindingFlags.Public ||| BindingFlags.NonPublic) 
    |> Array.filter FSharpType.IsUnion

type Name = 
    Name of string | NoName
    interface IReflective with
        member __.GetKnownTypes() = getKnownTypes<Name>()

type Coordinate = 
    Coordinate of float * float | NoCoordinate
    interface IReflective with
        member __.GetKnownTypes() = getKnownTypes<Coordinate>()

我已经忽略了attribute 的问题,因为我不确定我是否理解那里的目标。

免责声明:我是初学者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2013-05-07
    • 2020-05-02
    • 2015-10-23
    • 2020-06-20
    相关资源
    最近更新 更多