Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# use System.Type as Generic parameter

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

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

Session.Linq<MyType>() 

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

What I have is:

System.Type typeOne; 

But I cannot perform the following:

Session.Linq<typeOne>() 

How can I use a Type as a Generic parameter?

like image 935
Jan Avatar asked Jan 12 '11 10:01

Jan


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

C dalam Latin berapa?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).

Bahasa C dibuat pertama kali oleh siapa dan tahun berapa?

Bahasa pemrograman C ini dikembangkan antara tahun 1969 – 1972 oleh Dennis Ritchie. Yang kemudian dipakai untuk menulis ulang sistem operasi UNIX. Selain untuk mengembangkan UNIX, bahasa C juga dirilis sebagai bahasa pemrograman umum.


1 Answers

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.

like image 106
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet