[英]Using reflection and transform C# to F# code
我正在嘗試將一些 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
模塊中的函數而不是Select
和Where
擴展方法來執行相同的操作。 等價物:
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.toList
或Seq.toArray
調用,但這取決於您要對結果做什么。 在上面,結果是seq<list<string>>
,即不可變 F# 字符串列表的IEnumerable
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.