简体   繁体   中英

Get the actual type from a Type variable

I am trying to get a type from a Type variable. For example:

Type t = typeof(String);
var result = SomeGenericMethod<t>();

An error happens on the second line, because t is not a type , it's a variable. Any way to make it a type?

To make an instance of a generic based on a Type, you can use reflection to get an instance of the generic with the type you want to use, then use Activator to create that instance:

Type t = typeof (string); //the type within our generic

//the type of the generic, without type arguments
Type listType = typeof (List<>); 

//the type of the generic with the type arguments added
Type generictype = listType.MakeGenericType(t); 

//creates an instance of the generic with the type arguments.
var x = Activator.CreateInstance(generictype);

Note that x here will be an object . To call functions on it, such as .Sort() , you'd have to make it a dynamic .

Please Note that this code is hard to read, write, maintain, reason about, understand, or love. If you have any alternatives to needing to use this sort of structure, explore those thoroughly .

Edit : You can also cast the object you receive from the Activator , such as (IList)Activator.CreateInstance(genericType) . This will give you some functionality without having to resort to dynamics.

No, you cannot know the value of a Type object at compile time, which is what you would need to do in order to use a Type object as an actual type. Whatever you're doing that needs to use that Type will need to do so dynamically, and not require having a type known at compile time.

An ugly workaround using reflection:

Class with generic Method

public class Dummy {
        public string WhatEver<T>() {
            return "Hello";
        }    
    }

Usage

 var d = new Dummy();
 Type t = typeof(string);
 var result = typeof(Dummy).GetMethod("WhatEver").MakeGenericMethod(t).Invoke(d, null);

On class instantiation see Max's solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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