You need to enable JavaScript to run this app. 如何将使用反射的C#泛型转换方法改写为符合F#语法的对应实现
优惠活动
大模型
产品
解决方案
定价
更多

如何将使用反射的C#泛型转换方法改写为符合F#语法的对应实现

修正后的F#实现方案

你原先的实现存在以下几处问题:

  • 属性获取逻辑错误:typeof<T>本身就是T对应的Type实例,额外调用GetType()会拿到System.Type类型自身的属性,而非你需要的T的业务属性
  • F#中空值比较运算符是<>而非!=
  • 不需要手动维护可变的ResizeArray做结果累加,直接用Seq.map链式处理更符合函数式编程习惯,也更简洁
  • 缺少返回值的类型向上转换,无法匹配你定义的抽象成员返回obj seq seq的要求

基础适配版本(符合抽象成员定义)

open System
open System.Reflection
open System.Collections.Generic

// 此处为泛型类示例,你可以替换为自己的类声明
type YourConverter<'T>() =
    abstract member ConvertToGoogleRowsData : rows:seq<'T> -> seq<seq<obj>>
    override this.ConvertToGoogleRowsData(rows) =
        let bindingFlags = BindingFlags.Public ||| BindingFlags.Instance
        // 直接获取T类型的公共实例属性
        let properties = typeof<'T>.GetProperties(bindingFlags)
        rows
        // 过滤空值
        |> Seq.filter (fun x -> x <> null)
        // 逐行映射属性值为字符串,转obj匹配返回类型要求
        |> Seq.map (fun item ->
            properties
            |> Seq.map (fun prop -> prop.GetValue(item).ToString() :> obj)
        )

完全对齐C#返回结构版本(返回List<IList<object>>兼容结构)

如果需要和原C#代码返回的结构完全一致,可以调整为以下实现:

override this.ConvertToGoogleRowsData(rows) =
    let bindingFlags = BindingFlags.Public ||| BindingFlags.Instance
    let properties = typeof<'T>.GetProperties(bindingFlags)
    rows
    |> Seq.filter (fun x -> x <> null)
    |> Seq.map (fun item ->
        properties
        |> Seq.map (fun prop -> prop.GetValue(item).ToString() :> obj)
        |> ResizeArray<obj> :> IList<obj>
    )
    |> ResizeArray<IList<obj>> :> seq<seq<obj>>

内容的提问来源于stack exchange,提问作者João Mateus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 20:06:05