【问题标题】:Using reflection and transform C# to F# code使用反射并将 C# 转换为 F# 代码
【发布时间】:2021-06-12 22:34:19
【问题描述】:

我正在尝试将一些 C# 代码移至 F#,并且我正在努力以特定的方法实现这一目标。缺少使用反射时如何使 Seq 和 Pipeline 正常工作。

这里是 C#

        public static List<IList<object>> ConvertTTypeToData<T>(IEnumerable<T> exportList)
        {
            var type = typeof(T);
            var exportData = new List<IList<object>>();

            var properties = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

            foreach (var item in exportList.Where(x => x != null))
            {
                var data = properties.Select(property =>
                {
                    return property.GetValue(item).ToString();                    

                }).ToArray();
                exportData.Add(data);
            }

            return exportData;
        }

不幸的是,这是我目前使用 F# 所取得的成果

        member this.ConvertToGoogleRowsData(rows) = 
            let bindingFlags = BindingFlags.Public ||| BindingFlags.Instance

            let prop = typeof(T)

            let properties = prop.GetType().GetProperties(bindingFlags)

            let array = new ResizeArray<'T>()

            let test = rows |> Seq.toList
                             |> Seq.filter (fun x -> x != null )
                             |> Seq.iter (fun item ->
                                    array.Add(properties
                                              |> Seq.map (fun prop -> prop.GetValue(item).ToString())))
    abstract member ConvertToGoogleRowsData :
        rows: 'T seq
            -> obj seq seq

好心人能帮帮我吗?

非常感谢您的建议和帮助。

谢谢!

【问题讨论】:

    标签: c# f# c#-to-f#


    【解决方案1】:

    即使在 C# 代码中,您也可以将其重写为仅使用 Select 而不是构造一个临时集合 exportData 并在迭代输入时将结果添加到集合中:

    return exportList.Where(x => x != null).Select(item =>
      properties.Select(property => 
        property.GetValue(item).ToString()).ToArray()
    )
    

    在 F# 中,您可以使用 Seq 模块中的函数而不是 SelectWhere 扩展方法来执行相同的操作。等价物:

    let bindingFlags = BindingFlags.Public ||| BindingFlags.Instance
    let typ = typeof<'T>
    let properties = typ.GetProperties(bindingFlags) |> List.ofSeq  
    
    rows 
    |> Seq.filter (fun item -> item <> null)
    |> Seq.map (fun item ->
      properties |> List.map (fun prop -> 
        prop.GetValue(item).ToString()) )
    

    根据您想要的结果数据类型,您可能需要插入一些Seq.toListSeq.toArray 调用,但这取决于您要对结果做什么。在上面,结果是seq&lt;list&lt;string&gt;&gt;,即不可变 F# 字符串列表的IEnumerable

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多