温馨提示×

c#如何获取object的属性值

小亿
302
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