如何使用反射访问内部类
如何访问程序集的内部类? 假设我想访问 System.ComponentModel.Design.DesignerHost。这里的 DesignerHost 是一个内部密封类。
如何编写代码来加载程序集和类型?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何访问程序集的内部类? 假设我想访问 System.ComponentModel.Design.DesignerHost。这里的 DesignerHost 是一个内部密封类。
如何编写代码来加载程序集和类型?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(2)
一般来说,您不应该这样做 - 如果类型已标记为内部,则意味着您不应该从程序集外部使用它。它可能会在以后的版本中被删除、更改等。
但是,反射确实允许您访问非公开的类型和成员 - 只需查找采用
BindingFlags
参数并包含BindingFlags.NonPublic< /code> 在您传递的标志中。
如果您有类型的完全限定名称(包括程序集信息),则只需调用
Type.GetType(string)
应该可以工作。如果您提前知道程序集,并且知道该程序集中的公共类型,那么使用typeof(TheOtherType).Assembly
获取程序集引用通常更简单,那么您可以调用Assembly.GetType(string)
。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 includeBindingFlags.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 usingtypeof(TheOtherType).Assembly
to get the assembly reference is generally simpler, then you can callAssembly.GetType(string)
.要加载程序集并键入您在示例中引用的内容:
To load the assembly and type you quoted in your example: