您如何在命令提示符窗口中编译和执行 .cs 文件?
一旦你编写了C#代码并保存它,你可以像执行其他代码一样使用命令提示符来执行它。
在命令提示符中,输入文件所在的目录,然后键入:
编译:
mcs yourfilename.cs
mono yourfilename.exe
mcs yourfilename.cs -out:anyname.exe
要执行:
mono anyname.exe
csc
命令轻松构建程序,并在开发人员命令提示符中使用应用程序名称运行您的应用程序。# File : csharp.ps1
# Purpose : Powershell Script to compile a csharp console application from powershell prompt
try {
# CSharp Compiler
#$csc = "C:\Windows\Microsoft.NET\Framework\v3.5\bin\csc.exe"
$csc = "C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe"
# NOTE: if this path doesn't work search Framework folder for csc.exe
$ErrorActionPreference = 'Stop'
if ($args.Count -eq 0) {
write-host "`nUSAGE: csharp.ps1 (console_application.cs)"
exit 1
}
$file = $args[0];
if (-not(test-path $file)) {
throw "file doesn't exist: $file"
}
$cmd = "$csc /nologo /t:exe /out:${file}.exe $file"
write-host -ForegroundColor Green "`nx: $cmd"
invoke-expression $cmd
}
catch {
write-host -ForegroundColor Red "`nEXCEPTION: $_"
}
finally {
write-host ""
}
// File: helloworld.cs
using System;
namespace MyProgram
{
class Program
{
public static void Main(string[] args)
{
Console.Write("Hello World...");
Console.ReadKey(true);
}
}
}
PS> .\csharp.ps1 helloworld.cs
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Roslyn
这是您可以找到支持C#7的C#编译器的位置,否则它将使用仅支持C#5的.NET 4编译器。
dotnet
这是很老的问题了。但是,如果你作为初学者提出问题来理解如何在控制台中使用编译器而不是Visual Studio CE(强烈推荐C#),你会陷入更深的.NET框架、库和SDK术语的困境。
如果像你这样的初学者看到我的答案:
1. 理解框架和SDK之间的区别。
2. 理解C#和.NET是什么。
3. 这个链接:https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/intro
你会在学习过程中逐渐掌握其余部分。但是,我建议你使用SDK而不是框架,并且大多数情况下都使用VS。至于我,我学习C#是为了Unity和游戏开发。
此外,Google是你的好朋友。提问,保持好奇心。
CompileCS.cmd
**,它允许您编译(并可选地运行)C#文件。它在内部使用csc.exe,并调用本地PC上找到的最新版本。您可以在StackOverflow上找到批处理程序'CompileCS'的链接,我在那里回答了如何获取最近安装的csc.exe。 - Matt