是否可以使用可选的库引用?(对于可修改的 Mod) [英] Are optional library references possible? (for moddable Mods)

查看:25
本文介绍了是否可以使用可选的库引用?(对于可修改的 Mod)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以告诉 Visual Studio 为我构建一个 .dll,该 .dll 仅在另一个引用(托管)库存在但仍将其作为引用时才加载它?

Is there any way I could tell Visual Studio to build me a .dll that loads another referenced (managed) library only if it exists but still have it as a reference?

基本上我希望能够从外部库中的类继承,并且只有当外部类存在时,我才会对其进行初始化.

Basically I want to be able to inherit from a class that is inside the external lib and only if it the external class exists I will initialize it.

更长的解释:

  • 我制作了一个带有 modding api 的游戏(通过 Assembly.LoadFrom)
  • 我希望模组可以模组化.假设我有 2 个 Mod A 和 Mod B.Mod A 提供了一个静态注册表来添加附加功能.因此,在 Mod B 中,我目前正在检查 Mod A 是否已加载,如果是,请使用 Mod As 静态注册表来注册我的添加项.
  • 问题是,为了在没有编译错误的情况下这样做,我必须在 Visual Studio 项目中添加 Mod A 作为 Mod B 的引用 - 如果 Mod A 不存在,这会导致 Mod B 无法加载.但它应该是一个可选的参考:/

像Lazy Library Referencing"这样的东西会很完美 - 只有在实际需要时才加载 lib 引用.

Something like "Lazy Library Referencing" would be perfect - where a lib reference is only loaded once it is actually needed.

推荐答案

".Net 中的程序集由 CLR 按需加载.通常,在使用类型的方法被 JIT 之前不会尝试加载程序集来自那个大会."(来自不同的 SO 答案)

"Assemblies in .Net are loaded on demand by the CLR. Typically an assembly load won't be attempted until a method is JIT'd which uses a type from that assembly." (from a different SO Answer)

我就知道!显然我可以应用我的可选依赖项方法!

I knew it! Apparently I do can apply my kind of approach of optional dependencies!

我发现问题是由于我加载这些模组的方式引起的.我正在遍历所有程序集类型,检查实现 IMod 的任何类,这显然导致加载了有问题的类,并且需要 CLR 加载依赖项.

I discovered the problem arises due to the way I was loading those mods. I was iterating over all the assembly types checking for any class that implements IMod, which obviously caused the class in question to be loaded and that required the CLR to load the dependency.

我现在调用 assembly.GetExportedTypes() 而不是调用 assembly.GetTypes() 并将相关类声明为内部类.现在,如果依赖项不存在,它将永远不会加载.

Instead of calling assembly.GetTypes() I now call assembly.GetExportedTypes() and declare the class in question as internal. Now it is never loaded if the dependency does not exist.

这篇关于是否可以使用可选的库引用?(对于可修改的 Mod)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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