当泛型参数来自多个程序集时按名称加载泛型类型
我需要仅从其全名创建一个类型,例如:“System.String”或“Tuple'2[string,Mytype]”。 字符串中没有有关程序集的信息。 代码如下。
private static Type LoadType(string typeName)
{
// try loading the type
Type type = Type.GetType(typeName, false);
if (type != null)
return type;
// if the loading was not successfull iterate all the referenced assemblies and try to load the type.
Assembly asm = Assembly.GetEntryAssembly();
AssemblyName[] referencedAssemblies = asm.GetReferencedAssemblies();
foreach (AssemblyName referencedAssemblyName in referencedAssemblies)
{
type = referencedAssembly.GetType(typeName, false);
if (type != null)
return type;
}
throw new TypeLoadException(string.Format("Could not load the Type '{0}'",typeName));
}
当类型不是泛型时,此方法有效。但对于泛型类型,迭代程序集总是会失败,因为没有程序集包含构建该类型所需的所有定义。
有没有办法在调用 GetTypes 时提供多个程序集进行类型解析?
I need to create a type from its full name only Ex: "System.String" or "Tuple'2[string,Mytype]".
there is no information about the assembly in the string.
Here is what the code look like.
private static Type LoadType(string typeName)
{
// try loading the type
Type type = Type.GetType(typeName, false);
if (type != null)
return type;
// if the loading was not successfull iterate all the referenced assemblies and try to load the type.
Assembly asm = Assembly.GetEntryAssembly();
AssemblyName[] referencedAssemblies = asm.GetReferencedAssemblies();
foreach (AssemblyName referencedAssemblyName in referencedAssemblies)
{
type = referencedAssembly.GetType(typeName, false);
if (type != null)
return type;
}
throw new TypeLoadException(string.Format("Could not load the Type '{0}'",typeName));
}
this method works when the type is not generic. But for generic types iterating through the assemblies always fails because no assemblies contains all the definitions required to build the type.
Is there a way to provide multiples assemblies for type resolution when calling GetTypes ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你将不得不以我认为困难的方式去做。幸运的是,这并不难。非常简单:
You're going to have to do it the hard way I think. Fortunately it's not that hard. Pretty straightforward:
像这样的东西......
例如
,或者,正如埃里克所说......如果你手头有类型,就构建它..
Something like this....
e.g.
or, as Eric says.. if you have the types in hand, just build it..
这是我获取任何类型的困难方法解决方案:
Here is my hard way solution to get any type:
如果格式为“t1[[t2, a2][t3, a3]], a1”,则有效:
If the format is ´t1[[t2, a2][t3, a3]], a1´, this works: