2009-08-30 30 views
20

Tengo una clase que crea una matriz estática de todas las propiedades, utilizando un constructor estático. También tengo una función - GetNamesAndTypes() - que enumera el nombre & tipo de cada propiedad en esa matriz.Usando PropertyInfo.GetValue()

Ahora quiero crear otra función de nivel de instancia - GetNamesAndTypesAndValues ​​() - que muestre el nombre & tipo de cada propiedad en la clase, así como el valor de esa instancia. ¿Como podría hacerlo? Aquí está el código que he escrito hasta ahora:

//StaticTest.cs 
using System; 
using System.ComponentModel; 
using System.Globalization; 
using System.Reflection; 

namespace StaticTest 
{ 
    public class ClassTest 
    { 
     private string m_A, m_B, m_C; 
     private static PropertyInfo[] allClassProperties; 

     static ClassTest() 
     { 
      Type type = typeof(ClassTest); 
      allClassProperties = type.GetProperties(); 

      // Sort properties alphabetically by name 
      // (http://www.csharp-examples.net/reflection-property-names/) 
      Array.Sort(allClassProperties, delegate(PropertyInfo p1, PropertyInfo p2) 
      { 
       return p1.Name.CompareTo(p2.Name); 
      }); 
     } 

     public int A 
     { 
      get { return Convert.ToInt32(m_A); } 
      set { m_A = value.ToString(); } 
     } 

     public string B 
     { 
      get { return m_B; } 
      set { m_B = value; } 
     } 

     public DateTime C 
     { 
      get { return DateTime.ParseExact("yyyyMMdd", m_C, 
            CultureInfo.InvariantCulture); } 
      set { m_C = String.Format("{0:yyyyMMdd}", value); } 
     } 

     public static void GetNamesAndTypes() 
     { 
      foreach (PropertyInfo propertyInfo in allClassProperties) 
      { 
       Console.WriteLine("{0} [type = {1}]", propertyInfo.Name, 
              propertyInfo.PropertyType); 
      } 
     } 

     public void GetNamesAndTypesAndValues() 
     { 
      foreach (PropertyInfo propertyInfo in allClassProperties) 
      { 
       Console.WriteLine("{0} [type = {1}]", propertyInfo.Name, 
              propertyInfo.PropertyType); 
      } 
     } 
    } 
} 

//Program.cs 
using System; 
using System.Collections.Generic; 
using StaticTest; 

namespace ConsoleApplication2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("[static] GetNamesAndTypes()"); 
      ClassTest.GetNamesAndTypes(); 
      Console.WriteLine(""); 

      ClassTest classTest = new ClassTest(); 
      classTest.A = 4; 
      classTest.B = @"bacon"; 
      classTest.C = DateTime.Now; 
      Console.WriteLine("[instance] GetNamesAndTypesAndValues()"); 
      classTest.GetNamesAndTypesAndValues(); 

      Console.ReadLine(); 
     } 
    } 
} 

He intentado utilizar propertyInfo.GetValue(), pero no pude conseguir que funcione.

Respuesta

33

En su ejemplo propertyInfo.GetValue(this, null) debería funcionar. Considere la posibilidad de alterar GetNamesAndTypesAndValues() de la siguiente manera:

public void GetNamesAndTypesAndValues() 
{ 
    foreach (PropertyInfo propertyInfo in allClassProperties) 
    { 
    Console.WriteLine("{0} [type = {1}] [value = {2}]", 
     propertyInfo.Name, 
     propertyInfo.PropertyType, 
     propertyInfo.GetValue(this, null)); 
    } 
} 
+11

Aunque bien para propiedades simples normales, esto va a fallar con propiedades indexador, que tienen una lista de argumentos no nulo según lo especificado por PropertyInfo.GetIndexParameters. –

Cuestiones relacionadas