gpt4 book ai didi

f# - 在 F# 中使用 System.Reflection 分配属性值

转载 作者:行者123 更新时间:2023-12-01 08:29:22 25 4
gpt4 key购买 nike

我在 C# 中有以下几行代码:

internal static object AssignMatchingPropertyValues(object sourceObject, object targetObject)
{
Type sourceType = sourceObject.GetType();
PropertyInfo[] sourcePropertyInfos = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var sourcePropertyInfo in sourcePropertyInfos)
{
var targetPropertyInfo = targetObject.GetType().GetProperty(sourcePropertyInfo.Name);
if (targetPropertyInfo != null)
{
targetPropertyInfo.SetValue(targetObject, sourcePropertyInfo.GetValue(sourceObject, null), null);
}
}
return targetObject;
}

我想在 F# 中实现一个等效的功能,所以我做了这样的事情:
member this.AssignMatchingPropertyValues(sourceObject, targetObject)=
let sourceType = sourceObject.GetType()
let sourcePropertyInfos = sourceType.GetProperties(BindingFlags.Instance)
let assignedProperities = sourcePropertyInfos
|> Seq.map(fun spi -> spi, targetObject.GetType().GetProperty(spi.Name))
|> Seq.map(fun (spi,tpi) -> tpi.SetValue(targetObject, spi.GetValue(sourceObject,null),null))
()

问题是它不起作用。我认为 b/c 是不变性的,我得到了一个新的集合。有没有办法引用原始集合?这是解决这个问题的正确途径吗?

最佳答案

这是您的 C# 的直接翻译,您的 F# 代码不是:

let AssignMatchingPropertyValues sourceObject targetObject =
let sourceType = sourceObject.GetType()
let targetType = targetObject.GetType()
let sourcePropertyInfos = sourceType.GetProperties(BindingFlags.Public ||| BindingFlags.Instance)
for sourcePropertyInfo in sourcePropertyInfos do
match targetType.GetProperty(sourcePropertyInfo.Name) with
| null -> ()
| targetPropertyInfo -> targetPropertyInfo.SetValue(targetObject, sourcePropertyInfo.GetValue(sourceObject, null), null)
targetObject

关于f# - 在 F# 中使用 System.Reflection 分配属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23898092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com