从此

C#.NET、CSharp 语法新特性

综合/最新

C#编程

通用

锁定 .NET SDK 版本 echo '{ "sdk": { "version": "9.0.100-preview.6.24328.19" } }' > my-project/global.json
  或通过命令生成 dotnet new globaljson --sdk-version 8.0.100 --force

添加仓库源 dotnet nuget add source https://api.nuget.org/v3/index.json -n nuget.org
  dotnet nuget add source https://someServer/myTeam -n myTeam -u myUsername -p myPassword

直接引用 C# 库项目 <ItemGroup><ProjectReference Include="D:\x\x.csproj" /></ItemGroup>
物理合并 C# 库项目 <Import Project="..\x\SharedProject.projitems" Label="Shared" />
发布至 NuGet 仓库 dotnet nuget push ".godot\x\x.1.0.0-alpha.$time.nupkg" --api-key [API KEY] --source "https://nuget.pkg.github.com/[USER]/index.json"

变量类型默认值:int i = default; // 即=0。
初始化:Button btn = new();
初始化器:new List{ new Player("x"), new Player("xx") }; // 比Java少写个大括号。
调父类构造函数:public class NewClass : FatherClass { public NewClass() : base() { } } // Java 则写在方法体内 super();
类型判断:typeof(IEnumerable).IsAssignableFrom(typeof(List)) // 左侧更抽象。
判null:ArgumentNullException.ThrowIfNull(obj);
重写(覆写)/隐藏:
  声明类型 obj = new 定义子类型(); // override 不关心声明类型,而 new 则会分开调用声明类型里的方法体。
  override(重写)关键词则会把基类同名方法也编译为子类方法体,但基类必须标注为abstract(无方法体)或virtual(有方法体)。
  new(隐藏)关键词用于子类方法隐藏基类同名方法,转为基类后,则调用基类的方法体。

返回多个值(ValueTuple):
  private (int, int) GetNumbers()
  {
    return (1, 2);
  }

记录定义:
  public record Range(string name, int? p = null)
  { public int min { get; init; } public int max { get; init; } public string x { get; init; } }
记录调用:new Range("x") { min = 1, max = 9 } // name字段外均可选。

析构函数:
    ~Attack() { GD.Print("GC Attack."); }

await/async多层:
  public async void layer1(){ await layer2(); }
  public async Task layer2(){ await layer3(); }

特性:
  变相支持自定义类的返回值: [MyAttribute(nameof(MyClass.MethodName))]

C# 14 为现存类(声明在入参)扩展实例方法或属性:
  public static class CollectionExtensions
  {
    extension(ICollection collection)
    {  // 列表类会多个属性 list.IsEmptyNew()
       public bool IsEmptyNew => this.Count == 0;
    }
  }


软件时效:
  var today = DateOnly.FromDateTime(DateTime.UtcNow);
  if (today > new DateOnly(2026, 2, 1))
  {
	var msg = "程序已过期,将于10秒后退出!";
	Task.Delay(10_000).ContinueWith(_ => { System.Environment.Exit(0); });
	MessageBox.Show(msg); // or OS.Alert(msg);
  }


使调库者能访问 protected internal readonly Node Wrapped;
  <ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
      <_Parameter1>arpg-statecharts</_Parameter1>
    </AssemblyAttribute>

    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
      <_Parameter1>Chinatown Ranger</_Parameter1>
    </AssemblyAttribute>
  </ItemGroup>

隐藏调库者同名类:
  <ItemGroup>
    <Compile Remove="addons\godot_state_charts\csharp\**" />
  </ItemGroup>

其他

AOT交叉编译 - https://learn.microsoft.com/zh-cn/dotnet/core/deploying/native-aot/cross-compile