如何使用反射访问内部类 [英] How to access internal class using Reflection
问题描述
如何访问程序集的内部类?假设我想访问 System.ComponentModel.Design.DesignerHost.这里的 DesignerHost 是一个内部的密封类.
How can I access an internal class of an assembly? Say I want to access System.ComponentModel.Design.DesignerHost. Here the DesignerHost is an internal and sealed class.
如何编写代码来加载程序集和类型?
How can I write a code to load the assembly and the type?.
推荐答案
一般来说,你不应该这样做 - 如果一个类型被标记为内部,这意味着你不应该这样做从程序集外部使用它.它可以在以后的版本中删除、更改等.
In general, you shouldn't do this - if a type has been marked internal, that means you're not meant to use it from outside the assembly. It could be removed, changed etc in a later version.
但是,反射确实允许您访问非公开的类型和成员 - 只需查找采用 BindingFlags
参数并包含 BindingFlags 的重载.NonPublic
在您传递的标志中.
However, reflection does allow you to access types and members which aren't public - just look for overloads which take a BindingFlags
argument, and include BindingFlags.NonPublic
in the flags that you pass.
如果您有类型的完全限定名称(包括程序集信息),则只需调用 Type.GetType(string)
应该可以工作.如果您事先知道程序集,并且知道该程序集中的公共类型,那么使用 typeof(TheOtherType).Assembly
获取程序集引用通常更简单,那么您可以调用 Assembly.GetType(string)
.
If you have the fully qualified name of the type (including the assembly information) then just calling Type.GetType(string)
should work. If you know the assembly in advance, and know of a public type within that assembly, then using typeof(TheOtherType).Assembly
to get the assembly reference is generally simpler, then you can call Assembly.GetType(string)
.
这篇关于如何使用反射访问内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!