在C#中枚举对象的属性(字符串)

Mat*_*att 41 .net c# linq properties

假设我有很多对象,它们有很多字符串属性.

是否有一种编程方式来浏览它们并输出属性名及其值,还是必须进行硬编码?

是否可能有LINQ方法来查询对象的'string'类型的属性并输出它们?

您是否需要对要回显的属性名称进行硬编码?

Ben*_*n M 78

使用反射.它远不及硬编码属性访问速度快,但它可以满足您的需求.

以下查询为对象'myObject'中的每个字符串类型属性生成一个具有Name和Value属性的匿名类型:

var stringPropertyNamesAndValues = myObject.GetType()
    .GetProperties()
    .Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
    .Select(pi => new 
    {
        Name = pi.Name,
        Value = pi.GetGetMethod().Invoke(myObject, null)
    });
Run Code Online (Sandbox Code Playgroud)

用法:

foreach (var pair in stringPropertyNamesAndValues)
{
    Console.WriteLine("Name: {0}", pair.Name);
    Console.WriteLine("Value: {0}", pair.Value);
}
Run Code Online (Sandbox Code Playgroud)

  • 而不是pi.GetGetMethod().Invoke(myObject,null)我宁愿使用pi.GetValue(myObject,null) - 更简单的阅读. (3认同)

Mar*_*age 14

您可以使用该GetProperties方法获取类型的所有属性.然后,您可以使用LINQ Where扩展方法筛选此列表.最后,您可以使用LINQ Select扩展方法或类似的方便快捷方式来投影属性ToDictionary.

如果要将枚举限制为具有类型的属性,String可以使用以下代码:

IDictionary<String, String> dictionary = myObject.GetType()
  .GetProperties()
  .Where(p => p.CanRead && p.PropertyType == typeof(String))
  .ToDictionary(p => p.Name, p => (String) p.GetValue(myObject, null));
Run Code Online (Sandbox Code Playgroud)

这将创建一个将属性名称映射到属性值的字典.由于属性类型是有限的,String因此可以安全地将属性值强制转换String为返回类型的类型IDictionary<String, String>.

如果您想要所有属性,您可以这样做:

IDictionary<String, Object> dictionary = myObject.GetType()
  .GetProperties()
  .Where(p => p.CanRead)
  .ToDictionary(p => p.Name, p => p.GetValue(myObject, null));
Run Code Online (Sandbox Code Playgroud)