November 17, 2009

Reflection to invoke objects

So where did the ComWrapper come from yesterday? What is the point of this article in regards to reflection? Well, in short I wanted to show some some of the classes that helped me with my new AzMan library. Here is the TypeUtilities class:

//using System.Reflection;
public class TypeUtilities
{
private static string ToString(Type[] types)
{
string str = "";

foreach (Type type in types)
{
if (str.Length != 0)
str += ", ";

str += type.Name;
}

return str;
}

public static object GetProperty(object obj, string prop)
{
PropertyInfo pi = obj.GetType().GetProperty(prop);
return pi.GetValue(obj, new object[0]);
}

public static object GetProperty(Type type, object obj, string prop)
{
PropertyInfo pi = type.GetProperty(prop);
return pi.GetValue(obj, new object[0]);
}

public static Type[] GetTypes(object[] parameters)
{
Type[] types = new Type[parameters.Length];

for (int it = 0; it < parameters.Length; it++)
{
Type type = parameters[it].GetType();

if (type == typeof(ComWrapper))
{
ComWrapper wrapper = (ComWrapper)parameters[it];
type = wrapper.Type;
parameters[it] = wrapper.Object;
}

types[it] = type;
}

return types;
}

public static object InvokeOverloaded(object obj, string method, params object[] parameters)
{
Type objType = obj.GetType();
Type[] types = GetTypes(parameters);
MethodInfo mi = obj.GetType().GetMethod(method, types);
Assert(mi, objType, method, types);
return mi.Invoke(obj, parameters);
}

public static object Invoke(object obj, string method, Type[] types, object[] args)
{
Type objType = obj.GetType();
MethodInfo mi = objType.GetMethod(method, types);
Assert(mi, objType, method, types);

try
{
return mi.Invoke(obj, args);
}
catch (Exception ex)
{
Logger.Error(ex);
throw;
}
}

public static void Assert(MethodInfo mi, Type objType, string method, Type[] types)
{
if(mi == null)
throw new Exception(string.Format("Can't find method: {0}.{1}({2})", objType, method, ToString(types)));
}
Using the above classes, I'll show how in my AzMan library I was able to do things like:
while (!(entity is AzStore)) {
entity = (IAzParent)TypeUtils.GetProperty(entity, "Parent");

No comments:

Post a Comment