I am having a little trouble with something I am working on. I initially created a generic layer that sits between my business objects and the data access layer which is working fine. I then recently read about something called Expression Trees which is apparently more efficient and has proven to be so as I swapped Activator.CreateInstance() with an expression and has improved my generic layer exponentially.
I am still doing some reading about the whole area (Expressions) but I came across some code which I want to try making generic. At the moment, you have to pass in a concrete type such as a string, int, decimal etc. I was this bit to be generic. I Tried a couple of things but failed. The bit I want generic is Action, I don't want to pass in a string I want to be able to pass in the type of the property generically, i.e. typeof(T).GetProperty("Forename").PropertyType. Is this possible? Was thinking of doing a switch statement which is kinda foo bar.
Thanks in advance, Onam.
public class TTT<T> where T : new()
{
public void Do(object t)
{
MethodInfo info = typeof(T).GetProperty("Forename").GetSetMethod();
ParameterExpression param = Expression.Parameter(typeof(string), "val");
MethodCallExpression call = Expression.Call(Expression.Constant(t), info,
new ParameterExpression[] { param });
Action<string> action = Expression.Lambda<Action<string>>(call, param).Compile();
action("hi");
}
}