gpt4 book ai didi

c# - 使用c#获取两个不同对象的公共(public)属性

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:11 25 4
gpt4 key购买 nike

我需要从两个不同类的对象中获取公共(public)属性(即具有相同名称的.properties)到一个数组中。但我无法在 Join 附近提供正确的语法。这是我的代码。请帮忙

        PropertyInfo[] objAllProps = SourceInstance.GetType().GetProperties();
PropertyInfo[] objAllProps_Target = TargetInstance.GetType().GetProperties();

PropertyInfo[] CommonProperties =
from allprops in objAllProps join
allprop_target in objAllProps_Target on
allprops.Name.Equals(allprop_target)
select new PropertyInfo[] {
allprop_target,
}
.ToArray<PropertyInfo>();

最佳答案

我建议使用不同 集合类型 HashSet<string>而不是 PropertyInfo[] :

   HashSet<string> NamesToFind = new HashSet<string>(SourceInstance
.GetType()
.GetProperties()
.Select(property => property.Name));

// Common properties: properties of TargetInstance such that
// there's a property of SourceInstance with the same name
PropertyInfo[] CommonProperties = TargetInstance
.GetType()
.GetProperties()
.Where(property => NamesToFind.Contains(property.Name))
.ToArray();

关于c# - 使用c#获取两个不同对象的公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44364909/

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