使用Assembly.LoadFrom加载通用类型

编程入门 行业动态 更新时间:2024-10-28 15:25:16
本文介绍了使用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加载通用类型

本文发布于:2023-11-13 11:46:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584277.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   类型   Assembly   LoadFrom

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!