简体   繁体   English

在运行时将对象转换为通用类型

[英]Cast object to generic type at runtime

I'm using reflection to call a generic method, this method returns an object which I'd like to cast to call a method on after. 我正在使用反射来调用泛型方法,该方法返回一个对象,我希望将其转换为之后调用的方法。

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 isn't known until runtime. T直到运行时才知道。 How can I cast objectSet to ObjectSet<T> to be able to call ToTraceString()? 如何将objectSet强制转换为ObjectSet <T>以能够调用ToTraceString()?

As TyCobb said, you have use even more reflection. 正如TyCobb所说,您已经使用了更多的反射。 Keep going until you get to some type that you can write the cast for, like string : 继续前进,直到找到可以为其编写强制类型转换的某种类型,例如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);

    //...
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM