C# 获取属性中的属性
本文关键字:属性 获取 | 更新日期: 2023-09-27 18:36:52
给定以下类:
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 中的属性。型?
注意:如果我在 svm 上使用普通的 GetProperties 方法。模型 I 得到 14 个属性,弹出各种属性信息字段,没有来自 TheModel 类的属性。
注2:好的,尝试使用这样的外部代码:
var svm = new SampleViewModel();
var props = typeof(SampleViewModel).GetProperties();
var innerprops = svm.Model.GetType().GetProperties();
这似乎有效,现在我需要弄清楚为什么当我在我的框架中使用 Activator.CreateInstance 创建的实例执行此操作时,同样不起作用。 :)
谢谢,庞姆
在 SampleViewModel 中获取属性 Model 的属性,您需要调用:
typeof(SampleViewModel.TheModel).GetProperties();
或
svm.Model.GetType().GetProperties();
PropertyInfo[] properties = svm.Model.GetType().GetProperties();
foreach (PropertyInfo p in properties)
Console.WriteLine(p.Name);
输出
Name
Age
Birthdate
如您所见,GetProperties() 也适用于模型