C# 使用 System.Type 作为通用参数 [英] C# use System.Type as Generic parameter

查看:31
本文介绍了C# 使用 System.Type 作为通用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要在数据库上查询的类型列表(System.Type).

I have a list of types (System.Type) which need te be queried on the database.

对于每种类型,我需要调用以下扩展方法(它是 LinqToNhibernate 的一部分):

For each of this types, I need to call the following extensionmethod (which is part of LinqToNhibernate):

Session.Linq<MyType>()

但是我没有 MyType,但我想改用 Type.

However I do not have MyType, but I want to use a Type instead.

我拥有的是:

System.Type typeOne;

但我不能执行以下操作:

But I cannot perform the following:

Session.Linq<typeOne>()

如何使用类型作为泛型参数?

How can I use a Type as a Generic parameter?

推荐答案

你不能,直接.泛型的重点是提供编译时类型安全,您可以在编译时知道您感兴趣的类型,并且可以使用该类型的实例.在您的情况下,您只知道 Type,因此您无法在编译时检查您拥有的任何对象是该类型的实例.

You can't, directly. The point of generics is to provide compile-time type safety, where you know the type you're interested in at compile-time, and can work with instances of that type. In your case, you only know the Type so you can't get any compile-time checks that any objects you have are instances of that type.

您需要通过反射调用该方法 - 如下所示:

You'll need to call the method via reflection - something like this:

// 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);

如果您需要经常使用这种类型,您可能会发现编写自己的泛型方法更方便,该方法调用它需要的任何其他泛型方法,然后通过反射调用您的方法.

If you need to use this type a lot, you might find it more convenient to write your own generic method which calls whatever other generic methods it needs, and then call your method with reflection.

这篇关于C# 使用 System.Type 作为通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆