如何忽略使用反射继承的类的所有隐藏属性?

问题描述 投票:1回答:2

我有一个问题,我需要从对象获取所有属性,然后排序属性并将某些属性的值发送到另一个服务。以下是代码示例:

public class Class1
{
    public string A { get; set; }
    public bool B  { get; set; }
}

public class Class2 : Class1 
{
    public new bool? B { get; set; }
    public bool C { get; set; }
}

我需要获取Class2的所有属性,但是当使用Class2.GetType()。GetProperties()时,结果包含来自Class2和Class1的B.这导致我的问题,因为循环遍历我发送B两次的每个属性,一个默认值为false,因为它从未设置,然后另一个具有由我的服务设置的正确值。我需要结果包含来自Class2的B,来自Class1的A和来自Class2的C,但忽略了Class1中的B,因为它已被new关键字隐藏。

我试过查看我可以使用的绑定标志,但它没有帮助。我能找到的最接近的标志是BindingFlags.DeclaredOnly标志,但是它从Class1中排除了A,所以它对我不起作用。

如果它被隐藏了,我将如何忽略原始属性?

c# system.reflection
2个回答
1
投票

您可以使用LINQ查询过滤掉隐藏的属性。

var allProps = typeof(Class2).GetProperties(
        BindingFlags.Instance | BindingFlags.Public
);

var thePropsYouWant = 
        from p in allProps
        group p by p.Name into g
        select g.OrderByDescending(t => t.DeclaringType == typeof(Class2)).First();

看到它在这里运行:https://dotnetfiddle.net/V5sGIs


2
投票

如果我理解你正确你需要Class2的所有属性和Class1的所有属性未在Class2中重新定义

您可以通过两次调用GetProperties来实现这一点:首先选择Class2中定义的所有内容然后访问Class1的类型并添加任何丢失的内容

var type = typeof(Class2);
var list = new List<PropertyInfo>();
list.AddRange(type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly));

var baseType = type.BaseType;
if (baseType != null)
{
    foreach (var propertyInfo in baseType.GetProperties())
    {
        if (list.All(p => p.Name != propertyInfo.Name))
            list.Add(propertyInfo);
    }
}

如果您打印该列表

foreach (var propertyInfo in list)
    Console.WriteLine($"From {propertyInfo.DeclaringType} > '{propertyInfo.Name}':{propertyInfo.PropertyType}");

你会看到类似的东西:

从Class2>'B':System.Nullable`1 [System.Boolean] 从Class1>'A':System.String

© www.soinside.com 2019 - 2024. All rights reserved.