问题描述
我的类型(System.Type的),它需要德要查询的数据库列表。
I have a list of types (System.Type) which need te be queried on the database.
对于每一个这种类型的,我需要调用以下extensionmethod(这是LinqToNhibernate的一部分):
For each of this types, I need to call the following extensionmethod (which is part of LinqToNhibernate):
Session.Linq<MyType>()
不过,我没有MyType的,但我想用一个类型来代替。
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?
推荐答案
您不能直接。仿制药的一点是要提供的编译时间的类型安全,在那里你知道你有兴趣在编译时的类型,并且可以与该类型的实例工作。在你的情况,你只知道键入
所以你不能得到任何编译时检查,你有什么对象是该类型的实例。
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作为通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!