zondag 27 november 2011

InvokeMethod Extension

This extension method is very handy. Now you can call any method by using reflection without knowing how to!

e.g. object o = new Car();
Key key = new Key();
o.InvokeMethod( "StartYourEngine", key );

/// 
/// Invokemethod versimpeld.
/// 
/// /// /// /// 
[MethodImpl(MethodImplOptions.NoInlining)]
public static object InvokeMethod(this object value, string method, params object[] args)
{
  if (value == null) return null;
  Type t = value is Type? (Type)value : value.GetType();
  Type[] argTypes;
  bool typeComplete = true;
  if (args != null)
  {
    argTypes = new Type[args.Length];

    for (int i = 0; i < args.Length; i++)                   
    {
       object a = args[i];
       InvokeMethodNullParameter nullParameter = a as InvokeMethodNullParameter;
       if (nullParameter != null)                     
       {                         
          argTypes[i] = nullParameter.ParameterType;          
          args[i] = null; 
       }
       else if (a != null)  
          argTypes[i] = a.GetType();                      
       else
          typeComplete = false;  
    } 
  }
  else
    argTypes = new Type[]{};             
  MethodInfo mi = typeComplete
                  ? ( value is Type ?
                      t.GetMethod(method, BindingFlags.Static  BindingFlags.Public, null, argTypes, new ParameterModifier[]{})
                     : t.GetMethod(method,argTypes)
                    )
                 : t.GetMethod(method);
  if (mi != null)
  {
    try
    {
      return mi.Invoke(value, args);
    }
    catch (Exception ex)
    { 
       throw new Exception("Extensions.InvokeMethod() error. Er is een fout opgetreden tijdens het invoken van method \"{0}\" op type \"{1}\""                         .Formatteer(method, value.GetType().FullName)                         , ex);                 
    }
  }
  return null;         
} 


You need this class too:
public class InvokeMethodNullParameter
{
/// 
///
/// 
/// public InvokeMethodNullParameter(Type type)
{
ParameterType = type;
}
/// 
///
/// 
public Type ParameterType { get; private set; }
}

Geen opmerkingen: