溫馨提示×

c#如何獲取object的屬性值

小億
687
2024-05-11 14:47:46
欄目: 編程語言

在C#中,您可以使用反射來獲取一個對象的屬性值。以下是一個示例代碼,演示如何獲取一個對象的屬性值:

using System;
using System.Reflection;

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

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

        Type type = person.GetType();
        PropertyInfo nameProperty = type.GetProperty("Name");
        PropertyInfo ageProperty = type.GetProperty("Age");

        string nameValue = (string)nameProperty.GetValue(person);
        int ageValue = (int)ageProperty.GetValue(person);

        Console.WriteLine("Name: " + nameValue);
        Console.WriteLine("Age: " + ageValue);
    }
}

在上面的示例中,我們首先使用反射獲取對象的類型,然后使用GetProperty方法獲取對象的屬性。最后,使用GetValue方法獲取屬性的值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女