問題描述
我可以從命令行運行 .NET 程序集的代碼嗎? (Can I run code from a .NET assembly from a command line?)
I have a .NET class library (as a .dll file) and that library contains a class with a static method. Is there a way to call that method from a command line?
‑‑‑‑‑
參考解法
方法 1:
Here is a guide on how to load a dll from Powershell and call methods in it.
The most important part of the post are these commands:
[C:\temp]
PS:25 > notepad MyMathLib.cs
(…)
[C:\temp]
PS:26 > csc /target:library MyMathLib.cs
Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001‑2005. All rights reserved.
[C:\temp]
PS:27 > [Reflection.Assembly]::LoadFile(“c:\temp\MyMathLib.dll”)
GAC Version Location
— ——‑ ——–
False v2.0.50727 c:\temp\MyMathLib.dll
[C:\temp]
PS:28 > [MyMathLib.Methods]::Sum(10, 2)
12
[C:\temp]
PS:29 > $mathInstance = new‑object MyMathLib.Methods
Suggestion: An alias for New‑Object is new
[C:\temp]
PS:30 > $mathInstance.Product(10, 2)
20
方法 2:
Have a look here, maybe?
http://blog.usepowershell.com/2009/03/exploring‑the‑net‑framework‑with‑powershell‑static‑members‑part‑4/
And you can load your own assembly using
[Reflection.Assembly]::LoadFile(“c:\mysource\mylib.dll”)
If you're unable or unwilling to use Powershell, you need to wrap the call for your static method with a console application, as stated in davecoulter's answer
方法 3:
Yes ‑‑ but you'll have to have a program with a Main()
method that references that .dll and can call it‑‑ say in a console application.
(by sharptooth、Anders Abel、J. Steen、davecoulter)