我需要从两个不同类的对象中获取公共(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/