There are a lot
of such classes in my project (very old and stable code, I can't do many changes to them, maybe slight changes are OK)
public class MyEntity
{
public long ID { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
public static GetMyEntity ( long ID )
{
MyEntity e = new MyEntity();
// load data from DB and bind to this instance
return e;
}
}
For some reasons, now I need to do this:
Type t = Type.GetType("XXX"); // XXX is one of the above classes' name
MethodInfo staticM= t.GetMethods(BindingFlags.Public | BindingFlags.Static).FirstOrDefault();// I'm sure I can get the correct one
var o = staticM.Invoke(...); //returns a object, but I want the type above!
If I pass "MyEntity" at beginning, I hope I can get o as MyEntity! Please NOTE that I know the "name of the class" only. MyEntity e = staticM.Invoke(...) as MyEntity;
can't be used here.
EDIT
I'm trying to resolve it with expressions.
ParameterExpression[] parameterExps = (from p in staticM.GetParameters()
select Expression.Parameter(p.ParameterType, p.Name)).ToArray();
MethodCallExpression methodCallExp = Expression.Call(staticM, parameterExps);
BlockExpression blockExpression = Expression.Block(methodCallExp);
LambdaExpression lambdaExp = Expression.Lambda(blockExpression, parameterExps);
var d = lambdaExp.Compile() as Func<XX1,XX2>;
In the sample MyEntity, XX1 will be long, XX2 will be MyEntity, but how can I write it to fit other cases?
Since no solutions, I'll continue using reflection to operate the return object...