获取嵌套对象的属性

时间:2016-05-20 14:42:23

标签: c# winforms

我试图获取对象的所有属性及其值。 我的代码在这里给了我"简单"的所有价值。我的对象的属性:

                    foreach (var prop in dataItem.Value.GetType().GetProperties())
                    {
                        if (prop.Name == "CurrentSample")
                        {
                           //Doesn't work
                           var internProperties = prop.GetType().GetProperties();
                           foreach (var internProperty in internProperties)
                           {
                                System.Diagnostics.Debug.WriteLine("internProperty.Name + " : " + internProperty.GetValue(prop, null));
                           }
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine(prop.Name + " : "+ prop.GetValue(dataItem.Value, null));
                        }
                    }

我的问题出在我的" CurrentSample"属性,它包含它自己的2个属性(TimeStamp和String)。 我无法找到检索这些信息的方法。

我试图采用相同的原则,但我根本没有得到正确的信息。 我可以通过使用简单的dataItem.Value.CurrentSample.Value或dataItem.Value.CurrentSample.TimeStamp来访问这些值,但是想知道一种更合适的方法来使它工作。

现在不是使用它们的值打印我的TimeStamp和Value,而是获得一个很大的属性列表,我想类属性的所有属性:

ReflectedType : MTConnectSharp.DataItem
MetadataToken : 385876007
Module : MTCSharp.dll
PropertyType : MTConnectSharp.DataItemSample
Attributes : None
CanRead : True
CanWrite : False
GetMethod : MTConnectSharp.DataItemSample get_CurrentSample()
SetMethod : 
IsSpecialName : False
CustomAttributes : System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeData]

2 个答案:

答案 0 :(得分:1)

我猜你这行有问题:

var internProperties = prop.GetType().GetProperties();

它应返回PropertyInfo属性,因为您没有先获取属性值。

使用:

var internProperties = prop.GetValue(dataItem.Value, null).GetType().GetProperties();

它应该更好。

为此:

System.Diagnostics.Debug.WriteLine("internProperty.Name + " : " + internProperty.GetValue(prop, null));

你仍然需要道具价值,而不是财产本身。

答案 1 :(得分:0)

这部分:

internProperty.GetValue(prop, null)

表示您尝试获取prop属性的值,即PropertyInfo个实例。相反,你应该使用:

if (prop.Name == "CurrentSample")
{
    object currentSample = prop.GetValue(dataItem.Value, null);
    var internProperties = prop.GetType().GetProperties();
    foreach (var internProperty in internProperties)
    {
        System.Diagnostics.Debug.WriteLine("internProperty.Name + " : " + internProperty.GetValue(currentSample , null));
    }
}

PS。我个人试图避免在任何反射代码中使用var - 它已经足够难以阅读。