How can I get the type I want?
Posted
by Danny Chen
on Stack Overflow
See other posts from Stack Overflow
or by Danny Chen
Published on 2010-06-03T11:05:15Z
Indexed on
2010/06/03
11:14 UTC
Read the original article
Hit count: 267
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.
© Stack Overflow or respective owner