views:

60

answers:

2

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...

+1  A: 

There's no way to get compile-time checking if your string "XXX" is generated dynamically (from user input, for example), and therefore there's no way to have o be anything but object.

If it's a hard-coded string, however, or if you otherwise know the type at compile-type, you can do a cast:

var o = (XXX)staticM.Invoke(...);
lc
It's not a hard-coding string, that's why I can't convert at last.
Danny Chen
+2  A: 

WHat are you going to do with the obejct once it has been returned?

If the caling code knows what it is, then it can be casted there.

Really you are crying out for interfaces here, as the return can be cast ot a known interface, then the appropriate methods can be called.

ck