循环遍历变量的所有属性.包括复杂类型
本文关键字:属性 包括 复杂 类型 遍历 变量 循环 | 更新日期: 2023-09-27 18:34:19
我有以下程序循环遍历变量的所有属性:
class Program
{
static void Main(string[] args)
{
var person = new Person {Age = 30, Name = "Tony Montana", Mf = new Gender {Male = true,Female = false}};
var type = typeof(Person);
var properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("{0} = {1} : Value= {2}", property.Name, property.PropertyType, property.GetValue(person, null));
}
Console.Read();
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public Gender Mf;
}
public class Gender
{
public bool Male;
public bool Female;
}
当我运行它时,我得到以下输出:
"Age = System.Int32 : Value= 30"
"Name = System.String : Value= Tony Montana"
我没有看到我的复杂类型人。如何遍历对象人员并获取人员类型。Mf 和人的属性。Mf(即人。Mf.Male等)?提前致谢
Mf 是一个字段,而不是一个属性。 将其更改为:
public Gender Mf { get; set; }
或者,或者,使用反射来遍历所有公共字段(但我认为你最好把它作为一个属性)。
你看不到它,因为它不是一个属性。
要解决此问题,
-
或将其定义为属性
-
或者也使用反射恢复字段
FieldInfo[] fields = type.GetFields()