在运行时将对象强制转换为泛型类型

reg*_*tar 3 c# generics reflection

我正在使用反射来调用泛型方法,该方法返回一个对象,我想转换该对象以在之后调用方法。

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>
    ...
}
Run Code Online (Sandbox Code Playgroud)

T 直到运行时才知道。如何将 objectSet 转换为 ObjectSet<T> 以便能够调用 ToTraceString()?

Jac*_*all 5

正如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);

    //...
 }
Run Code Online (Sandbox Code Playgroud)