如何使用具有该属性名称的字符串变量访问对象属性?

时间:2022-05-15 04:44:48

How do I do this in C#?

我如何在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 个解决方案

#1


Use reflection :

使用反射:

using System.Reflection;

...

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

#2


Use System.Reflection and PropertyInfo

使用System.Reflection和PropertyInfo

#1


Use reflection :

使用反射:

using System.Reflection;

...

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

#2


Use System.Reflection and PropertyInfo

使用System.Reflection和PropertyInfo