从不同程序集中的类名解析类型 [英] Resolve Type from Class Name in a Different Assembly

查看:20
本文介绍了从不同程序集中的类名解析类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法需要解析类的类型.此类存在于另一个程序集中,其命名空间类似于:

I have a method where I need to resolve the Type of a class. This class exists in another assembly with the namespace similar to:

MyProject.Domain.Model

我正在尝试执行以下操作:

I am attempting to perform the following:

Type.GetType("MyProject.Domain.Model." + myClassName);

如果执行此操作的代码与我尝试解析其类型的类在同一个程序集中,则此方法非常有用,但是,如果我的类在不同的程序集中,则此代码将失败.

This works great if the code that is performing this action is in the same assembly as the class whose type I am trying to resolve, however, if my class is in a different assembly, this code fails.

我确信有更好的方法来完成这项任务,但我在解析程序集和遍历其中的命名空间以解析我正在寻找的类的类型方面没有很多经验.有什么建议或技巧可以更优雅地完成这项任务吗?

I am sure there is a far better way to accomplish this task, but I have not had a lot of experience with resolving assemblies and traversing namespaces within to resolve the type of the class I am looking for. Any advice or tips to accomplish this task more gracefully?

推荐答案

你必须像这样添加程序集名称:

You'll have to add the assembly name like this:

Type.GetType("MyProject.Domain.Model." + myClassName + ", AssemblyName");

为避免歧义或如果程序集位于 GAC 中,您应该提供一个完全限定的程序集名称,如下所示:

To avoid ambiguity or if the assembly is located in the GAC, you should provide a fully qualified assembly name like such:

Type.GetType("System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

这篇关于从不同程序集中的类名解析类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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