วิธีการรัน C# ไฟล์เดียวโดยที่ไม่ต้องสร้างเป็นโปรเจ็คโดยใช้ .NET CLI
เนื่องจากได้รู้จักกับ LeetCode เว็บสำหรับฝึกฝนทักษะการเขียนโปรแกรม โดยที่มีหลายภาษามากๆ และแน่นอนมีภาษา C# ด้วย
แค่ติดตั้ง dotnet-script โดยใช้คำสั่ง
dotnet tool install -g dotnet-script// Filename: omnisharp.json
{
"script": {
// เพื่อให้รู้ว่าเราจะเขียน dotnet แบบ script
"enableScriptNuGetReferences": true,
// ใช้ .net 5
"defaultTargetFramework": "net5.0"
}
}ถ้าเราใช้คำสั่ง
dotnet script initจะสร้างไฟล์omnisharp.jsonแบบนี้ให้อัตโนมัติเลย
// Filename: HelloWorld.csx
public class HelloWorld {
public string GetString() {
return "Hello World";
}
}
Console.WriteLine(new HelloWorld().GetString());ถ้าเราสังเกตุเราสามารถเขียนคำสั่งนอก Class ได้เลย ซึ่งสะดวกมากๆ สำหรับการเขียน script
ใน Docs เค้าแนะนำให้ใช้
.csxเพราะว่าจะได้แยกแยะออกว่าอันนี้คือ scripts
.
├── HelloWorld.csx
└── omnisharp.json$ dotnet-script .\HelloWorld.csx
Hello Worldเราสามารถใช้ โดยการสร้าง Folder ไว้แล้ว รันคำสั่งใน Folder นั้นเลย
dotnet script initThis will create main.csx along with the launch configuration needed to debug the script in VS Code.
.
├── .vscode
│ └── launch.json
├── main.csx
└── omnisharp.json