PowerShell无法调用C# DLL中非静态方法的问题排查
问题描述
我尝试通过PowerShell脚本调用C#类库DLL中的方法,类库代码如下:
namespace DLLCalculator { public class Calculator { public static void addNumbers(int num1, int num2) { MessageBox.Show((num1 + num2).ToString()); } public void helloWorld() { MessageBox.Show("Hello World!"); } } }
我的PowerShell代码:
[Reflection.Assembly]::LoadFile("C:\Users\Admin\source\repos\DLLCalculator\DLLCalculator\bin\Debug\DLLCalculator.dll") [DLLCalculator.Calculator]::addNumbers(10,5) $Object = new-object DLLCalculator.Calculator $Object.helloWorld()
其中静态方法[DLLCalculator.Calculator]::addNumbers(10,5)可正常运行,弹出预期结果的消息框,但非静态方法调用部分无法工作,报错信息如下:
Method invocation failed because [DLLCalculator.Calculator] does not contain a method named 'helloWorld'. At C:\Users\Admin\source\repos\PowershellStarter\PowershellStarter\bin\Debug\test.ps1:4 char:1 + $Object.helloWorld() + ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound
明明方法存在,PowerShell却无法找到,请问可能是什么原因导致的?
问题原因与解决方法
- 大小写匹配问题:PowerShell调用.NET方法时默认区分大小写(取决于版本和执行环境),可以先执行
$Object | Get-Member查看对象的所有成员,确认helloWorld方法的准确大小写是否与调用时一致。 - DLL版本不匹配:你加载的可能不是最新编译的DLL。比如修改C#代码添加
helloWorld方法后未重新编译,或者加载了旧版本的DLL文件。解决方法:重新编译C#类库,确保PowerShell加载的是bin\Debug目录下最新生成的DLL。 - 程序集加载方式问题:
[Reflection.Assembly]::LoadFile的加载上下文可能存在异常,建议改用Add-Type -Path "C:\Users\Admin\source\repos\DLLCalculator\DLLCalculator\bin\Debug\DLLCalculator.dll"来加载程序集,该命令在PowerShell中更稳定,能确保程序集被正确加载到当前执行上下文。 - 方法访问修饰符异常:虽然代码中声明的是
public方法,但需确认编译后的DLL中该方法的访问级别是否确实为public。可以用ILSpy等反编译工具打开DLL,查看helloWorld方法的实际访问修饰符。
内容的提问来源于stack exchange,提问作者GoldNova
相关产品推荐
相关产品推荐

