c# - 获取嵌套对象的属性

标签 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 个自己的属性(时间戳和字符串)。 我找不到检索这些信息的方法。

我已尝试应用相同的原则,但我根本没有获得正确的信息。 我可以使用简单的 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]

最佳答案

我猜你对这一行有疑问:

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));

您仍然需要属性值,而不是属性本身。

关于c# - 获取嵌套对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37349649/

相关文章:

c# - Windows 窗体 PictureBox - 如何在窗体的特定区域显示图像

c# - HTMLAgilityPack 和 HTML 页面

c# - 将 WPF DrawingGroup 呈现为单个 ImageSource

c# - 将控件插入 Tab 键顺序的最佳方法?

c# - 当我创建 WPF 窗口时,Windows 窗体窗口改变了它的大小

C# - 将值添加到字符串数组,除非它们为 NULL

c# - Xamarin 链接器删除对第三方 dll 的引用

c# - 如何从 C# 代码在 Visual Studio 中创建 native DLL?

c# - DispatcherTimer 不触发

c# Focus() 似乎触发了 Leave() 方法