获取类的属性和字段的值,类型和名称 [英] Get value, type and names of properties and fields of a class

查看:143
本文介绍了获取类的属性和字段的值,类型和名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多与此问题类似的主题,但是,其中一些仅用于字段,其他仅用于属性.我需要一个代码片段来检索类的属性和字段类型名称.以下代码仅适用于属性,不适用于字段.我一次需要两者.

There are a ton of topics similar to this question, however, some of them are only for fields, the others are properties. I need a code snippet that retrieves values, types, and names of a class’s properties and fields. The following code works for only properties, not also for fields. I need both at once.

@Edit; 如果没有循环,则可以检索属性和字段的总数.

@ Edit2;我认为可以使用.Count属性来完成.

@Edit2; I think it can be done with .Count property.

我尝试过的

foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(item))
{
    string name = descriptor.Name;              // Name
    object value = descriptor.GetValue(item);   // Value
    var type = descriptor.PropertyType;         // Type
    Console.WriteLine($"{name}={value}={type}");
}

对于示例类,其输出为

humidity=abcd=System.String
temperature=123,12=System.Double
pressure=99=System.Int32

示例类

class ExampClass
{
    public string testFieldJustField = "so";
    public string humidity { get; private set; }
    public double temperature { get; private set; }
    public int pressure { get; private set; }

    public ExampClass(string h, double t, int p)
    {
        humidity = h;
        temperature = t;
        pressure = p;
    }
}

推荐答案

如果要在没有(显式)循环的情况下查询,可以尝试 Linq :

If you want to query without (explicit) loops, you can try Linq:

首先,我们需要所有public instance 属性,这些属性可以被读取 不是索引器:

First we want all public instance properties, which can be read and are not indexers:

  using System.Linq;

  ...

  var item = new ExampClass("abcd", 123.12, 99);

  ...

  //TODO: Specify with a help of BindingFlags which properties do you want
  var props = item
    .GetType()
    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Where(pi => pi.CanRead)                      // can be read
    .Where(pi => !pi.GetIndexParameters().Any())  // not an indexer
    .Select(pi => new {
      name = pi.Name,
      value = pi.GetValue(pi.GetGetMethod().IsStatic ? null : item),
      type = pi.PropertyType,
      kind = "property",                          
    });

第二,我们需要所有public instance 字段:

Second we want all public instance fields:

  //TODO: Specify with a help of BindingFlags which fields do you want
  var fields = item
    .GetType()
    .GetFields(BindingFlags.Public | BindingFlags.Instance)
    .Select(fi => new {
      name = fi.Name,
      value = fi.GetValue(fi.IsStatic ? null : item),
      type = fi.FieldType,
      kind = "field",
    });

最后,我们可以在Concat的帮助下组合这两个查询:

Finally, we can combine both queries with a help of Concat:

  var result = props
    .Concat(fields)
    .OrderBy(record => record.name) // let's have results ordered
    .Select(record => $"{record.name}={record.value}={record.type}");

  // string.Join in order to avoid loops
  Console.WriteLine(string.Join(Environment.NewLine, result));

  // If you want total numbers put Count() 
  int total = props
    .Concat(fields)
    .Count();

  Console.WriteLine(total); 

结果:

  humidity=abcd=System.String
  pressure=99=System.Int32 
  temperature=123,12=System.Double
  testFieldJustField=so=System.String 
  4

这篇关于获取类的属性和字段的值,类型和名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆