[英]Using reflection and transform C# to F# code
I'm trying to move some C# code to F# and I'm struggling to achive that in a specific method.我正在尝试将一些 C# 代码移动到 F# 并且我正在努力以特定方法实现这一目标。 Lack of how to Seq and Pipeline work properly when using reflection.缺乏使用反射时如何使 Seq 和 Pipeline 正常工作。
Here's in C#这是 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;
}
And unfortunately here is what I achieved at moment using F#不幸的是,这是我目前使用 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
Could some good soul help me?有好心人能帮帮我吗?
Advice and help much appreciated.非常感谢您的建议和帮助。
Thanks!谢谢!
Even in the C# code, you could rewrite this to just use Select
instead of constructing a remporary collection exportData
and adding the results to the collection as you iterate over the input:即使在 C# 代码中,您也可以将其重写为仅使用Select
而不是构造一个临时集合exportData
并在迭代输入时将结果添加到集合中:
return exportList.Where(x => x != null).Select(item =>
properties.Select(property =>
property.GetValue(item).ToString()).ToArray()
)
In F#, you can do the same by using functions from the Seq
module, instead of Select
and Where
extension methods.在 F# 中,您可以通过使用Seq
模块中的函数而不是Select
和Where
扩展方法来执行相同的操作。 The equivalent:等价物:
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()) )
Depending on what data type exactly you want as a result, you may need to insert some Seq.toList
or Seq.toArray
calls, but this depends on what you want to do with the result.根据您想要的结果数据类型,您可能需要插入一些Seq.toList
或Seq.toArray
调用,但这取决于您要对结果做什么。 In the above, the result is seq<list<string>>
, ie IEnumerable
of immutable F# lists of strings.在上面,结果是seq<list<string>>
,即不可变 F# 字符串列表的IEnumerable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.