【发布时间】:2020-12-17 10:04:13
【问题描述】:
我有一个私人ConcurrentDictionary 如下图:
#region Private Fields
private ConcurrentDictionary<string, string> properties = new ConcurrentDictionary<string, string>();
#endregion
我有一个带有get 的公共属性,如下所示:
#region Properties
public ConcurrentDictionary<string, string> Properties { get { return properties; } }
#endregion
我认为这是有效的,但在我的测试中,我仍然可以通过公共 Properties 属性和 TryAdd 等将内容添加到字典中。
我在同一个类中有一个名为 AddProperties 的方法,它接受 key 和 value 并将它们存储在私有字典中,但我希望 Properties 只能在其他类中读取。
【问题讨论】:
-
属性是只读 - 您不能修改属性值。但这与不能改变属性值所指的对象不同。您可以将属性类型更改为
IReadOnlyDictionary<string, string>,尽管调用者仍然可以转换回ConcurrentDictionary<string, string>。另请注意,这与 ASP.NET Core 无关 - 我将删除标记。
标签: c#