如何使用C#中的变量调用对象的属性,例如customer.&fieldName

Edw*_*uay 3 c#

在C#中,有一种方法可以使用变量调用对象的属性,如下所示:

string fieldName = "FirstName";
Console.WriteLine(customer.&fieldName);
Run Code Online (Sandbox Code Playgroud)

回答:

非常好,感谢快速解答,这就是我想要做的:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace TestLinqFieldIndex
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(new Customer { ID = 1, FirstName = "Jim", LastName = "Smith" });
            customers.Add(new Customer { ID = 2, FirstName = "Joe", LastName = "Douglas" });
            customers.Add(new Customer { ID = 3, FirstName = "Jane", LastName = "Anders" });

            var customer = (from c in customers
                            where c.ID == 2
                            select c).SingleOrDefault();

            string[] fieldNames = { "FirstName", "LastName" };
            foreach (string fieldName in fieldNames)
            {
                Console.WriteLine("The value of {0} is {1}.", fieldName, customer.GetPropertyValue(fieldName));
            }

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string GetPropertyValue(string fieldName)
        {
            PropertyInfo prop = typeof(Customer).GetProperty(fieldName);
            return prop.GetValue(this, null).ToString();
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Fre*_*els 6

你可以用反射做到这一点.

PropertyInfo prop = typeof(Customer).GetProperty ("FirstName");
Console.WriteLine (prop.GetValue (customer, null));
Run Code Online (Sandbox Code Playgroud)

甚至可以检索私有财产的价值.为此,您必须查看GetProperty接受绑定标志的重载方法.