C# 如何使用反射访问内部类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1259222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:20:04  来源:igfitidea点击:

How to access internal class using Reflection

c#reflectionclassinternal

提问by dattebayo

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.

如何访问程序集的内部类?假设我想访问 System.ComponentModel.Design.DesignerHost。这里的 DesignerHost 是一个内部的密封类。

How can I write a code to load the assembly and the type?.

如何编写代码来加载程序集和类型?。

采纳答案by Jon Skeet

In general, you shouldn'tdo 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 doesallow you to access types and members which aren't public - just look for overloads which take a BindingFlagsargument, and include BindingFlags.NonPublicin the flags that you pass.

但是,反射确实允许您访问不公开的类型和成员 - 只需查找带有BindingFlags参数的重载,并将其包含BindingFlags.NonPublic在您传递的标志中。

If you have the fully qualifiedname 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).Assemblyto get the assembly reference is generally simpler, then you can call Assembly.GetType(string).

如果您具有类型的完全限定名称(包括程序集信息),则只需调用即可Type.GetType(string)。如果您事先知道程序集,并且知道该程序集中的公共类型,那么typeof(TheOtherType).Assembly用于获取程序集引用通常更简单,那么您可以调用Assembly.GetType(string).

回答by Patrick McDonald

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");