using reflection
-
public Ts GetMany(BasicBO BO) where T : BasicBO { List BOList = DataAccess.Get(tc, BO); List TList = new List(); foreach (BasicBO bo in BOList) TList.Add((T)bo); // error occured in the following statement object result = typeof(Ts).GetType() .InvokeMember("ctor",BindingFlags.CreateInstance, null, null, null); typeof(Ts).GetMethod("AddRangeFromDB", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(result, new object[] { TList }); return (Ts)result; } error message is : Constructor on type 'System.RuntimeType' not found Ts is a generic list of basicBO. please explain it.
-
public Ts GetMany(BasicBO BO) where T : BasicBO { List BOList = DataAccess.Get(tc, BO); List TList = new List(); foreach (BasicBO bo in BOList) TList.Add((T)bo); // error occured in the following statement object result = typeof(Ts).GetType() .InvokeMember("ctor",BindingFlags.CreateInstance, null, null, null); typeof(Ts).GetMethod("AddRangeFromDB", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(result, new object[] { TList }); return (Ts)result; } error message is : Constructor on type 'System.RuntimeType' not found Ts is a generic list of basicBO. please explain it.
I'm not at my dev machine so I can't test this, but try removing
GetType()
from the line so you just haveobject result = typeof(Ts).InvokeMember("ctor", BindingFlags.CreateInstance, null, null, null);
My bet is that the
Type
instance you want is fromtypeof(Ts)
, nottypeof(Ts).GetType()
. DybsThe shout of progress is not "Eureka!" it's "Strange... that's not what i expected". - peterchen
-
public Ts GetMany(BasicBO BO) where T : BasicBO { List BOList = DataAccess.Get(tc, BO); List TList = new List(); foreach (BasicBO bo in BOList) TList.Add((T)bo); // error occured in the following statement object result = typeof(Ts).GetType() .InvokeMember("ctor",BindingFlags.CreateInstance, null, null, null); typeof(Ts).GetMethod("AddRangeFromDB", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(result, new object[] { TList }); return (Ts)result; } error message is : Constructor on type 'System.RuntimeType' not found Ts is a generic list of basicBO. please explain it.
If it's generic, you must have lost your generic parameters. You may also want to specify New in the where clause so you can instantiate the class directly rather than use Reflection. But I think one of the main problems is that the constructor's name is ".ctor". Also, when using Reflection, you may want to cache the MethodInfo rather than get it over and over again.
-
I'm not at my dev machine so I can't test this, but try removing
GetType()
from the line so you just haveobject result = typeof(Ts).InvokeMember("ctor", BindingFlags.CreateInstance, null, null, null);
My bet is that the
Type
instance you want is fromtypeof(Ts)
, nottypeof(Ts).GetType()
. DybsThe shout of progress is not "Eureka!" it's "Strange... that's not what i expected". - peterchen