c#如何获取object的属性值

1379
2024/4/28 14:47:46
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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方法获取属性的值。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C#中怎么使用DateTime.Compare()比较时间大小