Executing a method by parameter in C#
I'll start by I have no idea on the terminology on this or if it is even possible (I am pretty sure it can be done).
I have a chunk of code that is basically as follows:
DataTable dt = new DataTable();
if (string = "this")
dt = method1();
else if (string = "that")
dt = method2();
else if (string = "somethingelse")
dt = method3(datetime, datetime2);
else if (string = "anotherthing")
dt = method4(string);
....and so on....
I am trying to make this cleaner. The comparison string is in a table. My thought would be to do something more like the following:
if (row.parmtype = "date"){
dt = row.method(datetime, datetime2);
else
dt = row.method();
So the method I call would be stored in the table along with 开发者_如何学Gothe type of call it is (there are only 3 types so far). Each call returns a DataTable. Can I either get a sample for better yet, a resource on how to do this?
Realize that since I don't know what I am talking about, the above code isn't exactly what I am looking for, but is for the purpose of getting my point across.
you can do a dictionary like
var delegates = new Dictionary<string, Func<MyClass, DataTable>>()
{
{"somestr", x => x.Method1()}
};
if (delegates.ContainsKey(key))
delegates[key](this);
You have a couple of options (off the top of my head) that work in basically any version of the framework:
- Change your "if" nesting structure to a switch
- You could use reflection over the object if you are calling known functions on the object
- Lastly you could use a Command Pattern to implement a common "execute" function and do as you describe above passing the command and the data to the object and letting it decide what to do.
- You could also look into using delegates and events depending on your needs as well
Any of these should work depending on your requirements, the simplest "next step" from where you are is to probably change to a switch statement and then look at using the command pattern. Reflection can be great, but expensive if you are doing it at a high volume and you dont take care to use good caching. Fasterflect can help if you decide to go this direction.
In .NET 4.0 (maybe 3.5) you could also look at using dynamic and expression trees to do something similar, but this may be more code than you want to write for your current implementation.
You are probably looking for delegates.
精彩评论