Is there a way in F# to type-test against a generic type without specifying the instance type?

前端 未结 4 1878
春和景丽
春和景丽 2021-01-01 02:45

I\'m trying to pattern match against a few types that I care about for SQL generation. Ideally I\'d like to do this:

let rec getSafeValue record (prop: Prope         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 03:15

    When I put your code in F# Interactive, it seems to make 'record' a generic param. Maybe it works differently in the normal compiler. Anyway, it is probably picking up that obj type due to the first argument of GetValue being type obj.

    I'm sorry I can't test this right now, but give this a shot. The box function uses a generic param, so that might do the trick.

    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()
    

提交回复
热议问题