简体   繁体   English

从Type变量中获取实际类型

[英]Get the actual type from a Type variable

I am trying to get a type from a Type variable. 我试图从Type变量中获取一个类型。 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. 第二行发生错误,因为t不是type ,它是变量。 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创建泛型的实例,可以使用反射来获取要使用的类型的泛型实例,然后使用Activator创建该实例:

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 . 请注意,此处的x将是一个object To call functions on it, such as .Sort() , you'd have to make it a dynamic . 要调用它上面的函数,例如.Sort() ,你必须使它成为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) . 编辑 :您还可以转换从Activator接收的对象,例如(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. 不,您无法在编译时知道Type对象的值,这是您需要执行的操作才能将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. 无论您正在做什么,需要使用该Type将需要动态地执行此操作,并且不需要在编译时具有已知类型。

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 在类实例化上,请参阅Max的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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