【问题标题】:Reading properties using reflection使用反射读取属性
【发布时间】:2016-12-17 09:57:47
【问题描述】:

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

public object CurrentViewModel
        {
            get { return m_currentViewModel; }
            set
            {
                m_currentViewModel = value;
                OnPropertyChanged("CurrentViewModel");
            }
        }

假设 CurrentViewModel 在运行时返回一个实例类 VMParent。

我的 VMParent 看起来像这样:

public class VMParent
{
 public object BaseViewModel
        {
            get { return m_baseViewModel; }
            set
            {
                m_baseViewModel = value;
            }
        }
}

BaseViewModel 属性在运行时返回一个 VMBase 类的实例,该实例具有一定数量的属性。

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

请指点一下? 谢谢。

Type sourceType = CurrentViewModel.GetType();            
PropertyInfo[] sourcePI= sourceType.GetProperties();

【问题讨论】:

  • 为什么要通过反射?你有什么具体问题?为什么你不能为BaseViewModel 做呢?为什么BaseViewModel 不只是一个标准的基类,而不是被CurrentViewModel 包含?这个问题充其量是太宽泛了,实际上根本就不清楚。请提供一个很好的 minimal reproducible example 来展示您迄今为止所做的尝试,并准确解释该代码的作用以及您希望它做什么。

标签: c# wpf mvvm reflection


【解决方案1】:

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

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
    }
}

你可以随心所欲地继续繁殖到巢中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多