c#如何获取object的属性值

avatar
作者
筋斗云
阅读量: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方法获取属性的值。