如何使用包含属性名称的字符串变量访问对象属性?

9

我该如何在C#中实现这个功能?

using System;

namespace TestProperties28373
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer { FirstName = "Jim", LastName = "Smith", Age = 34};

            Console.WriteLine(customer.FirstName);

            string propertyName = "FirstName";
            Console.WriteLine(customer.&&propertyName); //PSEUDO-CODE

            Console.ReadLine();

        }
    }

    class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
}
2个回答

24

使用反射:

using System.Reflection;

...

PropertyInfo prop = typeof(Customer).GetProperty(propertyName);
object value = prop.GetValue(customer, null);

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接