如何获取 C# 对象的属性信息

本文关键字:对象 属性 信息 何获取 获取 | 更新日期: 2023-09-27 18:32:11

我正在尝试提取对象的属性信息,但属性信息不返回任何属性:

 [TestMethod]
    public void TestGetValueMethod()
    {
      var value = 23;
      System.Reflection.PropertyInfo[] propertyInfo = value.GetType ().GetProperties();
      //DTOPropertyInfo info = new DTOPropertyInfo(propertyInfo[0]);
      System.Diagnostics.Debug.WriteLine(propertyInfo.Length);
    }

属性信息长度返回 0。我错过了什么?

如何获取 C# 对象的属性信息

using System;
using System.Reflection;
class Example
{
    public static void Main()
    {
        string test = "abcdefghijklmnopqrstuvwxyz";
        // Get a PropertyInfo object representing the Chars property.
        PropertyInfo pinfo = typeof(string).GetProperty("Chars");
        // Show the first, seventh, and last letters
        ShowIndividualCharacters(pinfo, test, 0, 6, test.Length - 1);
        // Show the complete string.
        Console.Write("The entire string: ");
        for (int x = 0; x < test.Length; x++)
        {
            Console.Write(pinfo.GetValue(test, new Object[] {x}));
        }
        Console.WriteLine();
    }
    static void ShowIndividualCharacters(PropertyInfo pinfo, 
                                         object value,
                                         params int[] indexes)
    {
       foreach (var index in indexes) 
          Console.WriteLine("Character in position {0,2}: '{1}'",
                            index, pinfo.GetValue(value, new object[] { index }));
       Console.WriteLine();                          
    }                                      
}