如何让 Reflection.Emit 程序集访问生成程序集中的内部成员?

发布于 2024-07-13 03:44:18 字数 338 浏览 6 评论 0原文

对于我的一个项目,我需要在运行时生成一些类,我认为使用 Reflection.Emit 来完成会相当简单,但是当我运行一些调用方法的生成代码时,我收到了 MemberAccessExceptions标记在发电机组件内部。 有什么方法可以告诉运行时动态程序集应该能够直接访问我自己的代码吗? 我真的不想向我的图书馆的消费者公开暴露这些成员。


Regarding InternalsVisibleTo, I am unsure how I would go about using it in the case of dynamically generated assemblies. Is this even possible?

For one of my projects, I need to generate at run time some classes, and I thought it would be fairly simple to do using Reflection.Emit, but I'm getting MemberAccessExceptions when I run some of the generated code that calls methods that are marked internal in the generator assembly. Is there any way to tell the runtime that the dynamic assembly should be able to access my own code directly? I would really rather not publicly expose any of these members to consumers of my library.


Regarding InternalsVisibleTo, I am unsure how I would go about using it in the case of dynamically generated assemblies. Is this even possible?

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

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

发布评论

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

评论(2

晒暮凉 2024-07-20 03:44:19

InternalsVisibleTo 的工作原理是向其他人打开程序集。 因此,如果您想使用生成类型中的程序集 Foo,则必须在 AssemblyInfo.cs 中为 Foo 指定生成的程序集的名称。

如果您使用 AssemblyBuilder 类生成新程序集,则可以指定生成的程序集的名称。 此名称必须与程序集 Foo 中的 InternalsVisibleTo 属性使用的名称相匹配。

InternalsVisibleTo works by opening an assembly to others. So if you want to use assembly Foo from your generated types, you must specify the name of the generated assembly in AssemblyInfo.cs for Foo.

If you're emitting a new assembly using the AssemblyBuilder class, you can specify the name for the generated assembly. This name has to match the name used for the InternalsVisibleTo attribute in assembly Foo.

烦人精 2024-07-20 03:44:19

我认为生成程序集中的成员被标记为内部是有原因的。

您可以在公共方法中公开必要的功能,或者只剩下两个选择:InternalsVisibleTo(如评论部分中提到的@tuinstoel)或反射(使用反射您可以访问不同程序集中的非公共成员)。

I suppose there's a reason behind the fact that the members in your generating assembly are marked internal.

You can either expose the necessary functionality in public methods, or you are left with only two choices: InternalsVisibleTo (as @tuinstoel mentioned in the comments section) or Reflection (using reflection you can access non public members in different assemblies).

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