I am writing a program in C # (3.5 at the moment, but I will probably adapt to other versions as necessary), which uses a simple plug-in architecture to control input and output. Each plugin is a DLL that loads when the user selects the plugins to use.
Since the actual plugin class is not known until runtime, I use reflection in the wrapper class to call the methods and properties for accessing the plugins.
So far, I have used the following calling methods for the plugin:
public object Method(string methodName, params object[] arguments) {
Used as:
string[] headers = (string[]) Plugin.Method("GetHeaders", dbName, tableName);
This works well if the caller correctly returns the return value to the expected type. Plugins must implement certain interfaces, so the caller must know this type.
However, after some additional work with reflection, I received the following alternative form:
public T Method<T>(string methodName, params object[] arguments) { if (!Methods.ContainsKey(methodName)) { LoadMethod(methodName, arguments); } if (Methods[methodName].ReturnType != typeof(T)) { // Could also move this into LoadMethod to keep all the throwing in one place throw new NoSuchMethodException(methodName); } if (arguments != null && arguments.Length == 0) { arguments = null; } return (T) Methods[methodName].Invoke(Plugin, arguments); }
This one is used as:
string[] headers = Plugin.Method<string[]>("GetHeaders", dbName, tableName);
This version essentially moves casting to a method method. The caller obviously still needs to know the expected return type, but this will always be so. It does not work for void methods, but I can include a version of the method in it:
public void Method(string methodName, params object[] arguments) {
My question is, is one of them essentially better than the other (for a given value, "better")? For example, is it especially noticeably faster? Easier to understand? More supported?
I personally like the look of the latter, although I'm a little worried that my test testing of the return type ( Methods[methodName].ReturnType != typeof(T) ) may be too simplistic. Interestingly, it was originally !(Methods[methodName].ReturnType is T) , but it always seemed unsuccessful.
The closest existing question to this that I could find is the General method for casting input , and some of the answers suggested that the last method is more expensive than the first, but there are not so many details (the question is more about the implementation of the method, and not that it is better).
Clarification: This is a manual, very limited plug-in system that does not use IPlugin. I am more interested in the question of whether general methods are inherently better / worse than expected that the caller will use in this situation.