您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

C#使用System.Type作为通用参数

C#使用System.Type作为通用参数

您不能直接这样做。泛型的目的是提供 编译时 类型安全性,使您在编译时知道您感兴趣的类型,并且可以使用该类型的实例。在您的情况下,您仅知道,Type因此您无法进行任何编译时检查,以确保您拥有的任何对象都是该类型的实例。

您需要通过反射来调用方法-类似于:

// Get the generic type deFinition
MethodInfo method = typeof(Session).getmethod("Linq", 
                                BindingFlags.Public | BindingFlags.Static);

// Build a method with the specific type argument you're interested in
method = method.MakeGenericMethod(typeOne);
// The "null" is because it's a static method
method.Invoke(null, arguments);

如果你需要使用这种类型很多,你可能会发现更方便地编写需要调用哪些其他任何泛型方法你自己的泛型方法,然后调用 用反射法。

c# 2022/1/1 18:23:05 有386人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶