c#如何获取object的属性值

   2024-10-19 5310
核心提示:在C#中,您可以使用反射来获取一个对象的属性值。以下是一个示例代码,演示如何获取一个对象的属性值:using System;using Syste

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

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号