Translate

sábado, 1 de marzo de 2014

C# Reflection: How to obtain fields, properties, etc.. from a Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Clases
{
    class AClassExample
    {
        private int _Id;
        private string _Name;
        private DateTime _Date;
                      
        public int Id
        {
            get { return _Id; }
            set { _Id = value; }
        }

        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        public DateTime Date
        {
            get { return _Date; }
            set { _Date = value; }
        }

        public AClassExample(int anId, string aName, DateTime aDate)
        {
            _Id = anId;
            _Name = aName;
            _Date = aDate;
        }
    }

    class Program
    {
        public static void printObject(AClassExample aClass)
        {
            Type myObjectType = typeof(AClassExample);

            //Get Fields from object           
            System.Reflection.FieldInfo[] fieldInfo =              myObjectType.GetFields(System.Reflection.BindingFlags.Instance |
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public );
           //The  Binding flags allows to show the private fields

            foreach (System.Reflection.FieldInfo field in fieldInfo)
                Console.WriteLine(field.Name + ':' + field.GetValue(aClass));


            //Getting Properties from object
            System.Reflection.PropertyInfo[] propInfo = myObjectType.GetProperties();

            foreach (System.Reflection.PropertyInfo prop in propInfo)
                Console.WriteLine(prop.Name + ':' + prop.GetValue(aClass));

        }

        static void Main(string[] args)
        {
            AClassExample example = new AClassExample(2,"Un nombre",DateTime.Now);
            printObject(example);
            Console.ReadLine();
        }
    }
}

No hay comentarios: