I've got a class that receives an object from other unknown modules and so I have to do reflection on the object to get its data, call its methods, etc.
To simplify the code to reflect on the object, I'm building this class:
using System;
namespace ApplicationCore.Helpers
{
class ObjectReflector
{
public object TheObject { get; set; }
public Type TheType { get; set; }
public ObjectReflector(object theObject)
{
TheObject = theObject;
TheType = theObject.GetType();
}
public string GetObjectShortName()
{
return TheObject.GetType().Name;
}
public string GetObjectLongName()
{
return TheObject.GetType().ToString();
}
public T GetPropertyValue<T>(string propertyName)
{
return (T)TheType.GetProperty(propertyName).GetValue(TheObject, null);
}
public T GetMethodValue<T>(string methodName, object[] parameters)
{
return (T)TheType.GetMethod(methodName).Invoke(TheObject, parameters);
}
}
}
So that I have nice, clean code that looks like this:
namespace ApplicationCore.Presenters
{
public class SmartFormPresenter
{
public UserControl View { get; set; }
public string ShortName { get; set; }
public string LongName { get; set; }
public string FirstName { get; set; }
public int Age { get; set; }
public int AgePlusTwo { get; set; }
public SmartFormPresenter(object o)
{
SmartFormView smartFormView = new SmartFormView();
View = smartFormView;
smartFormView.DataContext = this;
ObjectReflector or = new ObjectReflector(o);
ShortName = or.GetObjectShortName();
LongName = or.GetObjectLongName();
FirstName = or.GetPropertyValue<string>("FirstName");
Age = or.GetPropertyValue<int>("Age");
AgePlusTwo = or.GetMethodValue<int>("GetAgeInTwoYears", null);
}
}
}
But now I need to make methods e.g. to read out not an int but a List<Contract>
so that I'm going to have to get a List<object>
and then reflect on the "object" etc.
So I'm thinking that this has been done before. Is there any kind of tool or class in .NET called ObjectReflector that will help me simplify the reflection of an object as I'm doing above?