从Type变量中获取实际类型

时间:2016-08-11 21:09:16

标签: c# generics typeof

我试图从Type变量中获取一个类型。例如:

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

第二行发生错误,因为t不是type,它是一个变量。有什么办法让它成为一种类型?

3 个答案:

答案 0 :(得分:7)

要基于Type创建泛型的实例,可以使用反射来获取要使用的类型的泛型实例,然后使用Activator创建该实例:

%2

请注意,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); 此处为x。要调用其中的函数,例如object,您必须将其设为.Sort()

请注意此代码难以阅读,编写,维护,理解,理解或喜爱。如果您有任何替代方案需要使用此类结构,请完整地探索

修改:您还可以投射从dynamic收到的对象,例如Activator。这将为您提供一些功能,而无需采用动态。

答案 1 :(得分:5)

不,您无法在编译时知道Type对象的值,这是为了将Type对象用作实际类型而需要执行的操作。无论您正在做什么,需要使用Type需要动态地执行此操作,并且不需要在编译时具有已知类型。

答案 2 :(得分:2)

使用反射的丑陋的解决方法:

具有通用方法的类

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

<强>用法

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

关于类实例化,请参阅Max的解决方案

相关问题