使用PowerShell加载.NET DLL提示[MyMathLib.Methods]类型找不到的解决求助
解决PowerShell加载.NET DLL后无法找到类型的问题
问题场景
你编写的.NET类库代码:
namespace MyMathLib { public class Methods { public Methods() { } public static int Sum(int a, int b) { return a + b; } public int Product(int a, int b) { return a * b; } } }
编译为net6.0的DLL后,使用以下PowerShell命令加载并调用静态方法:
$AssemblyPath = "D:\Visual Studio code\MyMathLib\bin\Debug\net6.0\MyMathLib.dll" $bytes = [System.IO.File]::ReadAllBytes($AssemblyPath) [System.Reflection.Assembly]::Load($bytes) [MyMathLib.Methods]::Sum(10, 2)
执行后报错:
Unable to find type [MyMathLib.Methods].
At line:4 char:1
- [MyMathLib.Methods]::Sum(10, 2)
+ CategoryInfo : InvalidOperation: (MyMathLib.Methods:TypeName) [], RuntimeException + FullyQualifiedErrorId : TypeNotFound
解决方案
确认PowerShell版本兼容性:net6.0属于.NET Core/.NET 5+系列,Windows PowerShell(默认随Windows安装的版本)基于.NET Framework,无法加载.NET Core/.NET 6+的程序集。需要使用PowerShell 7及以上版本(基于.NET Core/.NET 5+)来运行命令。
改用
Add-Type命令加载DLL:PowerShell中推荐使用Add-Type替代直接调用[System.Reflection.Assembly]::Load,它能更好地处理类型加载逻辑,修改后的命令如下:$AssemblyPath = "D:\Visual Studio code\MyMathLib\bin\Debug\net6.0\MyMathLib.dll" Add-Type -Path $AssemblyPath [MyMathLib.Methods]::Sum(10, 2)验证程序集是否成功加载:如果仍有问题,可以先检查程序集是否已加载到当前域:
[AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.FullName -like "*MyMathLib*" }如果没有输出,说明DLL未成功加载,需检查DLL是否损坏、路径是否正确(路径中的空格无需额外转义,PowerShell可识别带空格的路径)。
兼容Windows PowerShell的备选方案:如果必须使用Windows PowerShell,可以将.NET类库重新编译为.NET Framework兼容版本(比如net48),修改项目的目标框架后重新编译,再用原命令加载调用。
内容的提问来源于stack exchange,提问作者Chiranjit Saha
相关产品推荐
相关产品推荐

