从对象子级获取特定属性

本文关键字:属性 获取 对象 | 更新日期: 2023-09-27 18:00:44

我很难想出一个像样的方法来问这个问题,但我会尽力说明。

我正在处理一个类似这样的数据结构:

public Foo
{
     public Bar Bar {get;set;}
}
public Bar
{
    public SubTypeA TypeA {get;set;}
    public SubTypeB TypeB {get;set;}
    ...
}
public SubTypeA
{
    public int Status {get;set;}
    ...
}

请注意,我无法为此更改数据结构。

Bar类中有许多不同的类型,它们内部都有不同的属性,但它们共同的是Status的属性。

如果给定一个类型为Foo的对象,我需要做的是记录其中Bar对象中每个项目的状态。不过,并不是每个SubType每次都有一个值,有些可能是null。

我可以通过使用下面这样的递归函数来循环所有属性来管理它。虽然我认为这并不理想,因为循环可能会变得很大,因为每个SubType上可能有很多属性。

private void GetProperties(Type classType, object instance)
{
    foreach (PropertyInfo property in classType.GetProperties())
    {
        object value = property.GetValue(instance, null);
        if (value != null) 
        {
            if (property.Name == "Status")
            {
                Record(classType, value);
            }
            GetProperties(property.PropertyType, value);
        }
    }
}

这是解决这样一个问题的唯一方法吗?

编辑:根据Selman22给出的答案,我提出了另一个问题,我试图根据对象的状态和名称创建一个匿名对象。

var z = instance.GetType()
            .GetProperties()
            .Select(x => new 
                { 
                    status = x.GetValue(instance).GetType().GetProperty("status").GetValue(x, null), 
                    name = x.Name 
                })
            .ToList();

这是在尝试检索值时抛出Object does not match target type.错误。这在1班轮上可能吗?

从对象子级获取特定属性

Type类包含可用于检索特定属性的GetProperty(字符串名称,BindingFlags方法)。使用此方法,而不是循环遍历每个属性。

http://msdn.microsoft.com/en-us/library/system.type.getproperty(v=vs.110).aspx

// Get Type object of MyClass.
Type myType=typeof(MyClass);       
// Get the PropertyInfo by passing the property name and specifying the BindingFlags.
PropertyInfo myPropInfo = myType.GetProperty("MyProperty", BindingFlags.Public | BindingFlags.Instance);

您可以使用LINQ而不是递归来获取所有Status属性:

var barInstance = typeof(Foo).GetProperty("Bar").GetValue(fooInstance);
var statusProperties = barInstance.GetType()
            .GetProperties()
            .Select(x => x.GetValue(barInstance).GetType().GetProperty("Status"));