如何使用反射访问内部类

发布于 2024-08-02 08:09:35 字数 120 浏览 13 评论 0 原文

如何访问程序集的内部类? 假设我想访问 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?.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长发绾君心 2024-08-09 08:09:35

一般来说,您不应该这样做 - 如果类型已标记为内部,则意味着您不应该从程序集外部使用它。它可能会在以后的版本中被删除、更改等。

但是,反射确实允许您访问非公开的类型和成员 - 只需查找采用 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 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).

各空 2024-08-09 08:09:35

要加载程序集并键入您在示例中引用的内容:

Assembly design = Assembly.LoadFile(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll");
Type designHost = design.GetType("System.ComponentModel.Design.DesignerHost");

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");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文