How can I get the type I want?
- by Danny Chen
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.