C# 中添加 DLL 的方法
在 C# 中添加 DLL 主要有两种方法:
方法 1:使用项目引用
步骤 1:在解决方案资源管理器中,右键单击项目并选择“添加”>“引用”。 步骤 2:在“引用管理器”中,转到“浏览”选项卡并导航到 DLL 文件。 步骤 3:选中 DLL 文件并单击“添加”按钮。方法 2:使用 DllImport
步骤 1:在 C# 文件中,使用System.Runtime.InteropServices命名空间导入
DllImport属性。 步骤 2:声明要从 DLL 导入的方法,并指定 DLL 名称和方法名称。 步骤 3:使用
DllImport导入的方法。
示例代码:
<code class="c#">using System;
using System.Runtime.InteropServices;
public class Program
{
[DllImport("MyDll.dll")]
public static extern int Add(int a, int b);
public static void Main()
{
int result = Add(10, 20);
Console.WriteLine(result); // 输出:30
}
}</code> 