簡體   English   中英

從對象子級獲取特定屬性

[英]Getting specific properties from an object child

努力想出一種體面的方式來問/題這個問題,但我會盡力說明它。

我正在使用類似這樣的數據結構:

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.的錯誤Object does not match target type. 嘗試檢索值時。 1班輪有可能嗎?

類型類包含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"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM