我正在使用反射来调用泛型方法,这个方法返回一个对象,我想在之后调用一个方法。
public static string GetTableName(this ObjectContext context, Type T)
{
var method = typeof(ObjectContext).GetMethod("CreateObjectSet", new Type[]{});
var generic = method.MakeGenericMethod(T);
var objectSet = generic.Invoke(context, null);
var sqlString = objectSet.ToTraceString();
// doesn't work because ToTraceString() isn't a method of object
// it's a method of ObjectSet<T>
...
}
直到运行时才知道T.如何将objectSet转换为ObjectSet&lt; T&gt;能够调用ToTraceString()?
答案 0 :(得分:3)
正如TyCobb所说,你使用了更多的反思。继续前进,直到你找到一些你可以编写演员表的类型,比如string
:
public static string GetTableName(this ObjectContext context, Type T)
{
var method = typeof(ObjectContext).GetMethod("CreateObjectSet", new Type[] { });
var generic = method.MakeGenericMethod(T);
var objectSet = generic.Invoke(context, null);
var toTrace = typeof(ObjectSet<>).MakeGenericType(T).GetMethod("ToTraceString");
var sqlString = (string)toTrace.Invoke(objectSet, null);
//...
}