扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

c#如何获取object的属性值

扬州沐宇科技
2024-05-11 14:47:46
c#, Object

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

扫码添加客服微信