gpt4 book ai didi

c# - 为什么我可以使用带有只读自动属性的匿名集合初始值设定项,而不能使用对象初始值设定项

转载 作者:行者123 更新时间:2023-12-02 18:05:12 25 4
gpt4 key购买 nike

考虑以下具有只读(或仅 getter)属性的类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);

}

似乎我无法在构造期间将对象分配给只读自动属性 ​​ClientPermissions,而我可以使用匿名集合初始值设定项为其分配值

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" } };

最佳答案

这是对 ClientPermissions 引用的对象调用 Add 方法:

ClientPermissions = { "a1", "b1" }

它没有为该属性分配一个新对象,因此它是被允许的。

相反,这是无效的,因为您无法在构造后将新对象分配给该属性:

ClientPermissions = new HashSet { "a1", "b1" }

相关文档为here .

关于c# - 为什么我可以使用带有只读自动属性的匿名集合初始值设定项,而不能使用对象初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73413901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com