获取类的属性和字段的值,类型和名称

时间:2019-07-11 07:43:59

标签: c# .net generics

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

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

@ Edit2;我认为可以使用.Count属性来实现。

我尝试过的

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;
    }
}

2 个答案:

答案 0 :(得分:0)

如果要获取字段,则必须使用GetFields()方法

获取字段:

            ExampClass item = new ExampClass("h",5,5);
            foreach (var descriptor in typeof(ExampClass).GetFields())
            {
                string name = descriptor.Name;              // Name
                object value = descriptor.GetValue(item);   // Value
                var type = descriptor.FieldType;         // Type
                Console.WriteLine($"{name}={value}={type}");
            }

获取属性:

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}");
}

您无法通过GetProperties()方法获取类的字段

答案 1 :(得分:0)

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

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

  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 字段:

  //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 组合两个查询:

  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
相关问题