.Net:加载程序集时运行代码

编程入门 行业动态 更新时间:2024-10-27 11:24:27
本文介绍了.Net:加载程序集时运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以在加载程序集时运行一些代码,而无需在加载代码中执行任何特定操作?我正在寻找的是一个类型的静态构造函数.

Is it possible to run some code when an assembly is loaded, without doing anything specific in the loading code? What I am looking for is like a static constructor on a type.

例如:

程序集 A 不知道程序集 B,但 B 知道 A.如果加载了 B,程序集 A 需要知道有关 B 的某些信息.当运行时(引用或显式)加载程序集 B 时,我希望执行一段调用程序集 A 中方法的代码(静态方法或属性).

Assembly A does not know about Assembly B, but B does know about A. Assembly A needs to know certain things about B if B is loaded. When Assembly B is loaded by the runtime (referenced, or explicit), I want a piece of code (static method or attribute) to be executed that calls a method in Assembly A.

这个问题的根本原因是在序列化 A 中的类型时遇到未知类型,该类型包含来自 B 的类型,因为使用接口在编译时未知.

The root cause of this problem is unknown types being encountered when serializing a type in A that contains types from B not known at compile time as interfaces are used.

推荐答案

CLR 支持 模块初始值设定项.您必须破解 C++/CLI 代码或 ilasm.exe 才能使用它们.

The CLR supports module initializers. You'd have to hack C++/CLI code or ilasm.exe to use them.

更新:从 .NET 5 开始,C# 也直接支持 [ModuleInitializer] 属性

UPDATE: directly supported in C# as well since .NET 5 with the [ModuleInitializer] attribute

更多推荐

.Net:加载程序集时运行代码

本文发布于:2023-11-14 13:21:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587323.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时运   加载   代码   程序   Net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!