是否可以在 X++ 代码中使用 C# .dll 文件而不将其添加到引用中?

问题描述 投票:0回答:1

我有以下问题:我们开发了一个 C# 类,我们计划在 X++ 类中使用它。所以,我们创建了一个.dll文件,并在X++项目中通过引用添加了它。

但是,如果我们将代码上传到存储库并将其克隆到其他机器并尝试构建模型,我们将得到一堆错误,其中使用 C# 类的 X++ 类无法找到它。所以我们必须再次添加这个.dll文件。

我想请问X++类是否可以动态找到这个.dll文件而无需每次都添加引用?这对我们很重要,因为它可能会在未来引起一些问题。

如果您能帮助解决这个问题或提供一些建议,我将非常高兴。

c# dll interop axapta x++
1个回答
0
投票

您可以通过使用 .NET 反射 API 在运行时加载程序集,然后使用这些相同的 API 调用程序集来执行此操作。 这是一个一般的例子:

Type type = asm.GetType("YourNamespace.YourClass");
System.Object obj = Activator::CreateInstance(type);
MethodInfo method = type.GetMethod("YourMethod");
var result = method.Invoke(obj, null);

在此代码中:

Assembly::LoadFrom loads the DLL from the specified path.
asm.GetType gets a Type object representing a type in the loaded assembly.
Activator::CreateInstance creates an instance of the specified type.
type.GetMethod gets a MethodInfo object representing a method of the specified type.
method.Invoke calls the specified method on the specified object.

但是,请注意这种方法有一些局限性和潜在问题:

您将失去编译时类型检查,这意味着调用 DLL 时的任何错误(例如调用不存在的方法)只会在运行时检测到。

如果更新了 DLL(例如,如果添加、删除方法或更改其签名),您将需要相应地更新您的 X++ 代码。

使用反射可能比直接调用方法慢。

尽管存在这些限制,但如果您需要在 X++ 中使用 .NET 程序集而不添加对项目的引用,则使用反射在运行时加载 .NET 程序集可能是一个很好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.