如何获取C#对象

时间:2016-01-28 08:28:04

标签: c# propertyinfo

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

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

propertyInfo.Length返回0.我缺少什么?

1 个答案:

答案 0 :(得分:0)

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