考虑以下具有只读(或只读)属性ClientPermissions的类:
internal class Client
{
public string? ClientId { get; set; }
public HashSet<string> ClientPermissions { get; } = new(StringComparer.Ordinal);
public HashSet<string> ClientTokens { get; set; } = new(StringComparer.Ordinal);
}
我似乎不能在构造期间将对象分配给只读自动属性ClientPermission,而我可以使用匿名集合初始值设定项为其赋值
SO 5646285给出一个提示 对于对象初始值设定项,DotNet编译器实际上将其编译为使用对象创建,然后再添加这些值.
好的...但是为什么我可以使用匿名集合初始值设定项而不是这个只读自动属性呢?
// Works - no complaints from compiler when I use collection initializer on read-only auto-property ClientPermissions
var sc1 = new Client() { ClientId = "c1", ClientPermissions = { "a1", "b1" }, ClientTokens = { "t1", "t2" } };
// Works - no complaints from compiler when I use collection initializer on read-only auto-property and object initializer on normal/full auto-property
var sc2 = new Client() { ClientId = "c2", ClientPermissions = { "a1", "b1" }, ClientTokens = new HashSet<string>{ "t1", "t2" } };
// DOES NOT COMPILE - Compiler complains with a CS0200: Property or indexer '...' cannot be assigned to -- it is readonly
// auto-initialize syntax
var sc3 = new Client() { ClientId = "c3", ClientPermissions = new HashSet<string> { "a1", "b1" }, ClientTokens = new HashSet<string> { "t1", "t2" } };