[英]How to access internal class using Reflection
How can I access an internal class of an assembly? 如何访问程序集的内部类? Say I want to access System.ComponentModel.Design.DesignerHost.
假设我想访问System.ComponentModel.Design.DesignerHost。 Here the DesignerHost is an internal and sealed class.
这里的DesignerHost是一个内部密封的类。
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. 但是,反射确实允许您访问非公共类型和成员 - 只需查找带有
BindingFlags
参数的重载,并在您传递的标志中包含BindingFlags.NonPublic
。
If you have the fully qualified name of the type (including the assembly information) then just calling Type.GetType(string)
should work. 如果您具有该类型的完全限定名称(包括程序集信息),则只需调用
Type.GetType(string)
。 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)
. 如果您事先知道程序集,并且知道该程序集中的公共类型,那么使用
typeof(TheOtherType).Assembly
来获取程序集引用通常更简单,那么您可以调用Assembly.GetType(string)
。
To load the assembly and type you quoted in your example: 要加载您在示例中引用的程序集和类型:
Assembly design = Assembly.LoadFile(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll");
Type designHost = design.GetType("System.ComponentModel.Design.DesignerHost");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.