如何在不修改Main函数的情况下从命令行运行.NET C# DLL指定函数
无需修改DLL即可调用特定函数的实现方案
dotnet exec本身确实没有直接指定调用DLL中特定函数的参数,但有几种实用方法能满足你的需求:
方法1:用第三方全局工具dotnet-invoke
先安装这个全局工具:
dotnet tool install -g dotnet-invoke
之后直接调用目标函数就行,比如针对你的例子:
- 执行
PrintVersion函数:
dotnet invoke MyApp.dll MyApp.Program.PrintVersion
- 执行
Version函数并输出返回值:
dotnet invoke MyApp.dll MyApp.Program.Version
这个工具靠反射加载DLL并执行指定函数,完全不用修改原DLL的Main方法。
方法2:自己写个极简启动器
如果不想用第三方工具,写个几十行的控制台程序就能搞定。这个程序接收DLL路径、完整类名、函数名作为参数,通过反射执行目标函数:
using System; using System.Reflection; namespace FuncInvoker; class Program { static void Main(string[] args) { if (args.Length < 3) { Console.WriteLine("用法:dotnet FuncInvoker.dll <DLL路径> <完整类名> <函数名>"); return; } var dllPath = args[0]; var className = args[1]; var methodName = args[2]; var assembly = Assembly.LoadFrom(dllPath); var type = assembly.GetType(className); var method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (method == null) { Console.WriteLine($"没找到函数 {methodName}"); return; } var result = method.Invoke(null, null); if (result != null) { Console.WriteLine(result); } } }
编译这个程序后,用它调用目标DLL的函数:
dotnet FuncInvoker.dll MyApp.dll MyApp.Program PrintVersion
或者调用Version:
dotnet FuncInvoker.dll MyApp.dll MyApp.Program Version
这个启动器可以反复用,任何DLL的静态函数都能调用。
方法3:用PowerShell直接调用
不想编译额外程序的话,PowerShell自带的反射能力也能实现:
- 执行
PrintVersion(非公开静态函数):
$assembly = [System.Reflection.Assembly]::LoadFrom("MyApp.dll") $type = $assembly.GetType("MyApp.Program") $method = $type.GetMethod("PrintVersion", [System.Reflection.BindingFlags]'Static, NonPublic') $method.Invoke($null, $null)
- 执行
Version(公开静态函数)并输出结果:
$assembly = [System.Reflection.Assembly]::LoadFrom("MyApp.dll") $type = $assembly.GetType("MyApp.Program") $method = $type.GetMethod("Version") $result = $method.Invoke($null, $null) Write-Host $result
直接在PowerShell里跑这段脚本就能得到你要的输出。
内容的提问来源于stack exchange,提问作者zacfromaustinpowder
相关产品推荐
相关产品推荐

