如何使用Reflection访问内部类 [英] How to access internal class using Reflection
问题描述
如何访问程序集的内部类?
说我想访问System.ComponentModel.Design.DesignerHost。这里的DesignerHost是一个内部和密封的类。
如何编写代码来加载程序集和类型?
一般来说,不应该这样做 - 如果一个类型已被标记为内部,这意味着你不打算从程序集之外使用它。
但是,反射 允许您访问不公开的类型和成员 - 只是寻找重载,它需要一个 BindingFlags
参数,并包括 BindingFlags.NonPublic
在你传递的标志。 / p>
如果您具有类型的完全限定名称(包括程序集信息),则只需调用 Type.GetType(string)
应该可以正常工作。如果您事先知道程序集,并且知道该程序集中的公共类型,那么使用 typeof(TheOtherType).Assembly
来获取程序集引用通常比较简单,可以调用 Assembly.GetType(string)
。
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.
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.
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)
.
这篇关于如何使用Reflection访问内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!