C# 的 namespace 及 Top-Level
經過多年的發展,C# 也來到了第十版,這次主要講兩個方便的改進,就是命名空間及 Top-Level,首先是命名空間,已經能簡化為下列這樣:
namespace TestNamespaceConsoleApp.Libs;
public class TestClass
{
public TestClass()
{
Field1 = new List<string>();
SortedDictionary<string, string> dic = new SortedDictionary<string, string>();
}
public List<string> Field1 { get; set; }
}
除此之外,在專案中常常要在各 cs 檔中輸入重覆的 using xxxx;
這類的程式碼,現在只要這樣輸入,對整個專案的 cs 檔都有效:
global using System;
global using System.Collections.Generic;
global using System.Linq;
但在 csproj 檔中的預設值關係,即使把 using
全部拿掉,還是能正常運作,但如果把 ImplicitUsings
的值改成 disable
,就需要用上 using
關鍵字:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
另外就是 Top-Level,現在的 Program.cs 檔中的程式碼可以簡化如下:
Console.WriteLine("Hello, World!");
沒錯!真正的 Hello World 就該這樣!
參考資料