从 .NET 中的字符串获取 Type 对象的最佳方法
在 .NET 中将字符串转换为 Type 对象的最佳方法是什么?
要考虑的问题:
- 该类型可能位于不同的程序集中。
- 该类型的程序集可能尚未加载。
这是我的尝试,但它没有解决第二个问题
Public Function FindType(ByVal name As String) As Type
Dim base As Type
base = Reflection.Assembly.GetEntryAssembly.GetType(name, False, True)
If base IsNot Nothing Then Return base
base = Reflection.Assembly.GetExecutingAssembly.GetType(name, False, True)
If base IsNot Nothing Then Return base
For Each assembly As Reflection.Assembly In _
AppDomain.CurrentDomain.GetAssemblies
base = assembly.GetType(name, False, True)
If base IsNot Nothing Then Return base
Next
Return Nothing
End Function
What is the best way to convert a string into a Type object in .NET?
Issues to consider:
- The type may be in a different assembly.
- The type's assembly may not be loaded yet.
This is my attempt, but it doesn't address the second issue
Public Function FindType(ByVal name As String) As Type
Dim base As Type
base = Reflection.Assembly.GetEntryAssembly.GetType(name, False, True)
If base IsNot Nothing Then Return base
base = Reflection.Assembly.GetExecutingAssembly.GetType(name, False, True)
If base IsNot Nothing Then Return base
For Each assembly As Reflection.Assembly In _
AppDomain.CurrentDomain.GetAssemblies
base = assembly.GetType(name, False, True)
If base IsNot Nothing Then Return base
Next
Return Nothing
End Function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 Type.GetType(string) 来执行此操作。 类型名称必须是程序集限定的,但该方法将根据需要加载程序集。 如果类型位于 mscorlid 或执行 GetType 调用的程序集中,则不需要程序集限定。
You can use Type.GetType(string) in order to do this. The type name must be assembly qualified but the method will load the assembly as necessary. The assembly qualification is not necessary if the type is in mscorlid or the assembly which executes the GetType call.
您可能需要为第二个调用 GetReferencedAssemblies() 方法。
you might need to call GetReferencedAssemblies() method for the second.
我认为您无法处理第二种情况,因为它取决于运行时来处理程序集的加载。 有多种方法可以动态加载程序集,但感觉很繁琐。
要查找具有您要查找的类的实际程序集,您可以使用对同一程序集中存在的另一个类的引用。 例如,您想要加载 App_Code 程序集,并且您知道 App_Code 中另一个名为
MyWidget
的类。现在您可以使用其名称加载另一个类:
I don't think you can handle the second case as its up to the runtime to handle the loading of the assemblies. There are ways to dynamically load assemblies but that feels heavy handed.
To find the actual assembly that has the class you are looking for you can use a reference to another class that exists in the same assembly. For example, you want to load an App_Code assembly and you know another class that's in App_Code called
MyWidget
.Now you can load the other class using its name: