使用反射并将C#转换为F#代码

c#

f#

c#-to-f#

我正在尝试将一些 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# 代码中,您也可以将其重写为仅使用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<list<string>>,即IEnumerable不可变的 F# 字符串列表。


以上是使用反射并将C#转换为F#代码的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>