【问题标题】:C# Getting properties in a propertyC# 获取属性中的属性
【发布时间】:2013-10-25 16:02:53
【问题描述】:

给定以下类:

public class SampleViewModel
{
    public TheModel Model { get; set; }

    public SampleViewModel()
    {
        this.Model = new TheModel();
    }

    public class TheModel
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime Birthdate { get; set; }
    }
}

实例化为:

var svm = new SampleViewModel();

如何通过反射列出 svm.Model 中的属性?

注意:如果我在 svm.Model 上使用普通的 GetProperties 方法,我会得到 14 个属性,弹出各种属性信息字段,并且没有来自 TheModel 类的属性。

注意 2:好的,尝试使用如下外部代码:

 var svm = new SampleViewModel();
 var props = typeof(SampleViewModel).GetProperties();
 var innerprops = svm.Model.GetType().GetProperties();

这似乎可行,现在我需要弄清楚为什么当我在框架内使用 Activator.CreateInstance 创建的实例时同样不起作用。 :)

谢谢,pom

【问题讨论】:

  • 如果一切都是公开的,那你为什么需要反思?
  • 这是你追求的:Type.GetProperties
  • 说:我正在编写一个模拟框架,所以我只需要通过反射来访问这些属性。 :)
  • Oleksii,是的,当然,但是如何?请参阅原始消息中的说明。
  • typeof(SampleViewModel).GetProperties

标签: c# reflection


【解决方案1】:

获取SampleViewModel中属性Model的属性,需要调用:

typeof(SampleViewModel.TheModel).GetProperties();

svm.Model.GetType().GetProperties();

【讨论】:

    【解决方案2】:
    PropertyInfo[] properties = svm.Model.GetType().GetProperties();
            foreach (PropertyInfo p in properties) 
                Console.WriteLine(p.Name);
    

    输出

    Name
    Age
    Birthdate
    

    如您所见,GetProperties() 也适用于 Model

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多