使用Assembly.LoadFrom加载通用类型 [英] Loading a generic type using Assembly.LoadFrom

查看:345
本文介绍了使用Assembly.LoadFrom加载通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在提到乔恩斯基特这里的答案:通实例化的System.Type作为一个类型参数的泛型类

Referring to the answer by Jon Skeet here: Pass An Instantiated System.Type as a Type Parameter for a Generic Class

我需要加载基于一般类型的名称的通用型,这是为通用类型参数的类型的名称。因此,从乔恩的例子,我将有:

I need to load a Generic type based on the name of the generic type, and the name of the type that is the type parameter for the generic. So from Jon's example I would have:

string genName = "MyNamespace.Generic";
string itemName = "System.String";



我有以下的代码,将基于类型的名称和一个完全合理的负载类型集名称/路径。它工作正常的简单类型

I have the following code that will load a type based on the name of the type and a fully justified assembly name/path. It works fine for "simple types"

public Type GetTypeOf(string assemblyPath, string className)
{
    var asmbly = System.Reflection.Assembly.LoadFrom(assemblyPath); //open assembly
    return asmbly.GetType(className, true, true); //throws error, not case sensitive
}



我希望利用这个如下

I was hoping to use this as follows:

//Get the types
var genTyp = GetTypeOf(genPath,genName);
var itemTyp = GetTypeOf(itemPath,itemName);

//Put them together:
var typ = getType.MakeGenericType(itemTyp);

这翻倒在了第一行 System.TypeLoadException 说明:

This falls over on the first line with a System.TypeLoadException stating:

Could not load type <TypeName here> from assembly <AssemblyName here>



我已经尝试了一些创建通用的排列,包括提供完整的类名称 MyNamespace.Generic<&System.String GT; 。它正常工作时,我指定一个非泛型类型从包含泛型类型相同的程序集加载。

I've tried a number of permutations of creating the generic, included supplying the full class name MyNamespace.Generic<System.String>. It works correctly when I specify a non-generic type to load from the same assembly that contains the generic type.

推荐答案

不幸的是,使用的GetType与泛型类型是不是可读。您必须使用完全限定的类型名称,即使是一般的参数:。例如, TestType<对象> 读这样的:

Unfortunately, using GetType with generic types is not that readable. You have to use the full qualified type name, even for the generic parameters:. For example, TestType<object> reads like this:

TestType`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

您的示例代码不包括类型声明,所以你要玩这个。你可以试试这个代码段,看看有什么调试器说:

Your sample code does not include the type declarations, so you have to play around with this. You can try this code snippet and take a look what the debugger says:

string typeName = typeof(MyNamespace.Generic<>).Name;
string fullTypeName = typeof(MyNamespace.Generic<>).FullName;



结果应该可以帮助您得到正确的类型名称。

The results should help you getting the correct type name.

这篇关于使用Assembly.LoadFrom加载通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆