【问题标题】:Is there a way in F# to type-test against a generic type without specifying the instance type?F# 中有没有一种方法可以在不指定实例类型的情况下对泛型类型进行类型测试?
【发布时间】:2010-06-30 16:01:39
【问题描述】:

我正在尝试针对一些我关心的用于 SQL 生成的类型进行模式匹配。理想情况下,我想这样做:

let rec getSafeValue record (prop: PropertyInfo) = 
    match prop.GetValue(record, null) with
    | :? string as str -> "'" + str + "'"
    | :? Option<_> as opt -> 
        match opt with
        | Some v -> getSafeValue v prop
        | None -> "null"
    | _ as v -> v.ToString()

问题在于,Option&lt;_&gt; 的类型参数被限制为与 record 的类型参数匹配,而 record 最终只是 obj。

我知道我可以做一些痛苦的基于反射的检查(检查它是否是泛型类型并且它是基于名称的选项类型),但如果可能的话,我宁愿避免这种情况.

【问题讨论】:

    标签: f#


    【解决方案1】:

    不,使用 F# 的内置结构没有很好的方法来做到这一点。但是,您可以为此类事情构建自己的可重用活动模式:

    open Microsoft.FSharp.Reflection
    open Microsoft.FSharp.Quotations
    open Microsoft.FSharp.Quotations.DerivedPatterns
    open Microsoft.FSharp.Quotations.Patterns
    
    let (|UC|_|) e o =
      match e with
      | Lambdas(_,NewUnionCase(uc,_)) | NewUnionCase(uc,[]) ->
          if (box o = null) then
            // Need special case logic in case null is a valid value (e.g. Option.None)
            let attrs = uc.DeclaringType.GetCustomAttributes(typeof<CompilationRepresentationAttribute>, false)
            if attrs.Length = 1
               && (attrs.[0] :?> CompilationRepresentationAttribute).Flags &&& CompilationRepresentationFlags.UseNullAsTrueValue <> enum 0
               && uc.GetFields().Length = 0
            then Some []
            else None
          else 
            let t = o.GetType()
            if FSharpType.IsUnion t then
              let uc2, fields = FSharpValue.GetUnionFields(o,t)
              let getGenType (t:System.Type) = if t.IsGenericType then t.GetGenericTypeDefinition() else t
              if uc2.Tag = uc.Tag && getGenType (uc2.DeclaringType) = getGenType (uc.DeclaringType) then
                Some(fields |> List.ofArray)
              else None
            else None
      | _ -> failwith "The UC pattern can only be used against simple union cases"
    

    现在你的函数可能看起来像这样:

    let rec getSafeValue (item:obj) = 
        match item with
        | :? string as str -> "'" + str + "'"
        | UC <@ Some @> [v] -> getSafeValue v
        | UC <@ None @> [] -> "null"
        | _ as v -> v.ToString()
    

    【讨论】:

    • 这是一个很好的方法。我最终做了类似的事情。
    【解决方案2】:

    如果没有协方差,这在 F# 中是行不通的。假设您对v 的类型为obj 感到满意,您希望能够将Option&lt;anything&gt; 视为Option&lt;obj&gt;。如果没有协方差,Option&lt;anything&gt; 和 Option&lt;obj&gt; 是独立的类型。

    【讨论】:

    • 需要明确的是,.NET(以及 F#)实际上并没有协方差。
    • @GaneshSittampalam - .NET(从 4.0 开始)确实具有协方差:msdn.microsoft.com/en-us/library/dd799517.aspx。我认为它没有在 F# 2.0 中实现的原因是因为 F# 在发布时主要针对 .NET 2.0。
    【解决方案3】:

    当我将您的代码放入 F# Interactive 时,它​​似乎使“记录”成为通用参数。也许它在普通编译器中的工作方式不同。无论如何,由于GetValue 的第一个参数是obj 类型,它可能会选择obj 类型。

    很抱歉,我现在无法对此进行测试,但请试一试。 box 函数使用一个通用参数,这样就可以解决问题。

    let rec getSafeValue record (prop: PropertyInfo) = 
        match prop.GetValue(box record, null) with
        | :? string as str -> "'" + str + "'"
        | :? Option<_> as opt -> 
            match opt with
            | Some v -> getSafeValue v prop
            | None -> "null"
        | _ as v -> v.ToString()
    

    【讨论】:

    • 同样的交易 - 它限制记录并选择输入'a
    【解决方案4】:

    Some v -> getSafeValue v prop 仅在 v 与记录具有相同类型时才有效。 (或从该类型派生)否则第一行将失败。你不能说 prop.GetValue(record,null) 除非 prop 指向的属性在第一个参数的上下文中是有意义的(也就是类型的一部分)。

    如果是同一类型,你可以这样做:

    let rec getSafeValue (record:'a) (prop: PropertyInfo) = 
        match prop.GetValue(box record, null) with
        | :? string as str -> "'" + str + "'"
        | :? Option<'a> as opt -> 
            match opt with
            | Some v -> getSafeValue v prop
            | None -> "null"
        | _ as v -> v.ToString()
    

    但如果 v 的类型是从 'a 派生的,它将匹配最后一种情况,因此要使上述工作正常,它们需要完全相同的类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多