溫馨提示×

c#怎么遍歷類的屬性值

c#
小億
256
2024-03-20 10:02:52
欄目: 編程語言

在C#中,可以通過反射的方式遍歷類的屬性值。下面是一個示例代碼:

using System;
using System.Reflection;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        Person person = new Person { Name = "Alice", Age = 30 };

        Type type = person.GetType();
        PropertyInfo[] properties = type.GetProperties();

        foreach (PropertyInfo property in properties)
        {
            string propertyName = property.Name;
            object propertyValue = property.GetValue(person);

            Console.WriteLine($"Property Name: {propertyName}, Value: {propertyValue}");
        }
    }
}

在上面的代碼中,我們定義了一個Person類,并創(chuàng)建了一個Person對象。然后使用反射獲取該對象的類型信息,并遍歷所有屬性,獲取屬性名和屬性值并打印出來。這樣就可以遍歷類的屬性值。

0