【问题标题】:Nested generic constraints in f#f# 中的嵌套通用约束
【发布时间】:2014-09-09 19:12:51
【问题描述】:

我正在尝试在泛型类 (Xceed.Wpf.Toolkit.NumericUpDown) 上定义扩展方法,但将该泛型限制为 Nullable<_>,但我无法弄清楚语法。我想要的本质是

type NumericUpDown<Nullable<_>> with
  member x.getVal() = x.Value.GetValueOrDefault()
  member x.setVal v = x.Value <- Nullable v

但这不会编译。我已经尝试了该主题的几种变体,但没有任何效果。有没有办法做到这一点?

【问题讨论】:

  • 嗨 - 我很晚才看到你想要一个扩展方法 - 但遗憾的是我不知道你试图扩展的类足以显示代码。我能给出的最好的办法是运行时检查 (match x with | :? System.Nullable&lt;'a&gt; as nA -&gt; nA.Value.GetValueOrDefault() | _ -&gt; Unchecked.defaultof&lt;'a&gt;)
  • 这对于 F# 样式的扩展是不可能的。您不能扩展泛型类型的特定情况。
  • @Daniel 仅供参考,见下文。
  • 对。使用 .NET 样式的扩展(通过 ExtensionAttribute)可以实现。

标签: generics f#


【解决方案1】:

我不知道您要扩展的类,但从 F# 3.1 开始,您应该能够编写和使用它:

open System.Runtime.CompilerServices

[<Extension>]
type NumericUpDownExtensions () =
  [<Extension>]
  static member getVal(x: NumericUpDown<Nullable<'a>>) = x.Value.GetValueOrDefault()
  [<Extension>]
  static member setVal(x: NumericUpDown<Nullable<'a>>, v) = x.Value <- Nullable v

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多