2008-11-27

The GetField method

Last month I wrote an article about clicking a button in a winforms application and in my code example I referred to the ReflectionUtil.GetField method.
The ReflectionUtil class is an utility class that I have used for several years and they provide a better/easier way to use reflection. They are in line to be converted as Extension methods for the Type type, but for now they are ordinary static methods.
I'll post the GetField method to allow the example to be complete.

#region public static object GetField(Type type, string name, object instance)
/// <summary>
/// Gets the field from the instance
/// </summary>
/// <param name="type">The <see cref="Type"/> that contains the field</param>
/// <param name="name">The name of the field</param>
/// <param name="instance">The instance to get the value from</param>
/// <returns>The value of the field</returns>
public static object GetField(Type type, string name, object instance) {
return InvokeMember(type, name, instance, BindingFlags.GetField | BindingFlags.Instance);
}
#endregion

The GetField only wraps the InvokeMember method. (I have more wrappers named GetProperty, SetField, SetProperty, InvokeMethod, InvokeStaticMethod etc. that calls the InvokeMember method)
#region public static object InvokeMember(Type type, string name, object instance, BindingFlags flags, params object[] parameters)
/// <summary>
/// Invokes the member
/// </summary>
/// <param name="type">The <see cref="Type"/> that contains the member</param>
/// <param name="name">The name of the member</param>
/// <param name="instance">The instance to invoke on</param>
/// <param name="flags">The <see cref="BindingFlags"/> to use</param>
/// <param name="parameters">The <see cref="object"/> array to pass as parameters</param>
/// <returns>The returnvalue</returns>
public static object InvokeMember(Type type, string name, object instance, BindingFlags flags, params object[] parameters) {
if (instance == null) {
flags |= BindingFlags.Static;
flags &= ~BindingFlags.Instance;
}

try {
return type.InvokeMember(name,BindingFlags.Public | BindingFlags.NonPublic | flags,null,instance,parameters);

//if the target threw an exception, throw this instead.
} catch (TargetInvocationException e) {

// if no exception is found, throw the TIException instead.
if (e.InnerException == null)
throw;
throw e.InnerException;
}
}
#endregion

Hope the click button example can make more sense now :)

No comments:

Post a Comment