.Net:加载程序集时运行代码 [英] .Net: Running code when assembly is loaded

查看:30
本文介绍了.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:加载程序集时运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆