【问题标题】:How to get all same properties from multiple classes?如何从多个类中获取所有相同的属性?
【发布时间】:2019-06-26 04:36:21
【问题描述】:

情况

我想显示多个类的所有通用属性。假设有一个具有属性“a”和“c”的类“A”,并且有一个具有属性“b”和“c”的类“B”......所以我基本上想获得属性“c”

有什么简单的方法吗?

编辑

对不起,我没有告诉我编程了什么。

我基本上有一个类列表,我想获取这些类的所有属性。

我的代码只是我尝试过的证明。

真实示例:Visual Studio

如果您选择 2 个按钮,那么您将看到这些按钮共同拥有的所有属性

代码

 private void GetAllProperties(ObservableCollection<DUIElement> selecteditems)
    {
        if (selecteditems == null)
            return;

        _properties.Clear();

        foreach (DUIElement item in selecteditems)
            foreach (PropertyInfo property in item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (property.PropertyType.Name != nameof(DPropertyViewModel))
                    continue;

                foreach (DUIElement itemnext in selecteditems)
                {
                    if (item.GroupName == itemnext.GroupName)
                        continue;

                    foreach (PropertyInfo propertynext in itemnext.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (propertynext.PropertyType.Name != nameof(DPropertyViewModel))
                            continue;

                        if (property.PropertyType.Name == propertynext.PropertyType.Name)
                        {
                            var prop = propertynext.GetValue(itemnext, null) as DPropertyViewModel;
                            _properties.Add(prop);
                        }
                    }
                }
            }

    }

【问题讨论】:

  • 我没有按照你的代码,因为我真的不知道你想要实现什么,但我的 Linq-Query 应该可以完成这项工作。

标签: c# reflection collections properties


【解决方案1】:

您可以这样做的一种方法是构建所有枚举项中存在的属性的列表:

List<string> Properties = null;

foreach (DUIElement item in selecteditems)
{
    // Check for first iteration
    if (Properties == null)
    {
        // Get name of properties from first iteration
        Properties = new List<string>();
        foreach (PropertyInfo item in item.GetType().GetProperties().ToList<PropertyInfo>())
            Properties.Add(item.Name);
    }
    else
    {
        // Check properties from current iteration
        foreach (PropertyInfo property in item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            // Remove properties where they do not exist in current property list
            if (!Properties.Contains(property.Name))
                Properties.Remove(property.Name);
        }
    }
}

这有效地复制了第一项中的所有属性,然后删除了剩余迭代中不存在的所有属性。

生成的属性名称将以Properties 结尾。

我不确定您是否只需要属性名称,或者您是否真的需要每个属性名称的 PropertyInfo。但是,您可以简单地使用Properties 列表来匹配selecteditems 中第一个对象中的PropertyInfo

【讨论】:

  • 您的回复。我会尝试按照你稍后所说的去做,如果有解决方案,我会把你的答案标记为正确。
猜你喜欢
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
相关资源
最近更新 更多