65.9K
CodeProject 正在变化。 阅读更多。
Home

如何遍历类的所有属性

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.20/5 (2投票s)

2013 年 10 月 11 日

CPOL
viewsIcon

97771

反射是 .NET 框架的一个重要功能,它使您能够在运行时获取有关对象的信息。 在本文中,我们将

反射是 .NET 框架的一个重要功能,它使您能够在运行时获取有关对象的信息。 在本文中,我们将使用反射遍历名为 Person 的类的所有属性。

using System;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();
        person.Age = 27;
        person.Name = "Fernando Vezzali";

        Type type = typeof(Person);
        PropertyInfo[] properties = type.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine("{0} = {1}", property.Name, property.GetValue(person, null));
        }

        Console.Read();
    }
}

Person 类扩展了 System.Object,并且没有实现任何接口。 它是一个简单的类,用于存储有关人员的信息

class Person
{
    private int age;
    private string name;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

© . All rights reserved.