Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用反射读取属性_C#_Wpf_Mvvm_Reflection - Fatal编程技术网

C# 使用反射读取属性

C# 使用反射读取属性,c#,wpf,mvvm,reflection,C#,Wpf,Mvvm,Reflection,在我的C#WPF应用程序中,我的MainViewModel具有以下属性: public object CurrentViewModel { get { return m_currentViewModel; } set { m_currentViewModel = value; OnPropertyChanged("CurrentViewModel

在我的C#WPF应用程序中,我的MainViewModel具有以下属性:

public object CurrentViewModel
        {
            get { return m_currentViewModel; }
            set
            {
                m_currentViewModel = value;
                OnPropertyChanged("CurrentViewModel");
            }
        }
假设CurrentViewModel在运行时返回实例类VMParent

我的父母是这样的:

public class VMParent
{
 public object BaseViewModel
        {
            get { return m_baseViewModel; }
            set
            {
                m_baseViewModel = value;
            }
        }
}
BaseViewModel属性在运行时返回具有一定数量属性的VMBase类实例

现在,单击MainViewModel.xaml中的一个按钮,使用反射,我需要读取CurrentViewModel和BaseViewModel的所有属性的值。 我可以为CurrentViewModel这样做,但不能为BaseViewModel这样做

有什么建议吗? 谢谢


我将通过打印属性的名称来说明此功能。如下所示

foreach (var p in sourcePI)
{
    Console.WriteLine(p.Name);
    var nested = p.GetValue(CurrentViewModel).GetType().GetProperties();
    foreach (var n in nested)
    {
        WriteLine(n.Name);
        // you can continue to nest as you like
    }
}

您可以继续传播到嵌套中,次数可以根据需要而定

为什么要通过反射?你有什么具体问题?为什么不能为
BaseViewModel
执行此操作?为什么
BaseViewModel
不只是一个标准的基类,而不是包含在
CurrentViewModel
中?这个问题充其量也太宽泛了,真的一点也不清楚。请提供一个很好的例子,说明您到目前为止已经尝试了什么,并准确地解释代码的作用以及您希望它做什么。
foreach (var p in sourcePI)
{
    Console.WriteLine(p.Name);
    var nested = p.GetValue(CurrentViewModel).GetType().GetProperties();
    foreach (var n in nested)
    {
        WriteLine(n.Name);
        // you can continue to nest as you like
    }
}