【问题标题】:How do I retrieve all the names of a type's properties as an array?如何将类型属性的所有名称作为数组检索?
【发布时间】:2014-11-10 17:04:01
【问题描述】:

假设我有一个Employee 类:

public class Employee
{
    public string Name    { get; set;}
    public string Address { get; set ;
}

现在我想用Employee类的属性名创建一个数组,即:

string[] employeeArray = { "Name", "Address" };

有没有办法在不硬编码属性名称的情况下实现这一点?

【问题讨论】:

  • 所以根据标签,你知道你需要使用反射。您对如何使用反射获取对象的属性列表进行了哪些研究?到目前为止,您尝试过的解决方案遇到了什么问题?

标签: c# .net reflection properties


【解决方案1】:

您可以使用反射来做到这一点,特别是使用Type.GetProperties method

这里有两种可能的解决方案;一个带有 LINQ,另一个没有(如果您针对的是较早版本的框架):

  • // using System.Linq;
    typeof(Employee).GetProperties().Select(p => p.Name).ToArray()
    
  • // using System;
    Array.ConvertAll(typeof(Employee).GetProperties(), p => p.Name)
    

请注意,Type.GetProperties() 只会看到公共实例属性。如果您还对静态属性或非公共属性的名称感兴趣,则需要致电a different overload of GetProperties

【讨论】:

    【解决方案2】:
    typeof(Employee).GetProperties().Select(x => x.Name).ToArray();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2019-12-27
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多