使用对象初始值设定项:
*在创建对象时,向对象的任何可访问字段或属性分配值
*可为构造函数指定参数或忽略参数
public class Cat {// Auto-implemented properties.public int Age { get; set; }public string? Name { get; set; }public Cat(){}public Cat(string name){this.Name = name;} }
Cat cat = new Cat { Age = 10, Name = "Fluffy" }; Cat sameCat = new Cat("Fluffy"){ Age = 10 };
详细参考:
https://learn.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers