集合属性应该是只读的-漏洞? [英] Collection properties should be read only - Loophole?

查看:130
本文介绍了集合属性应该是只读的-漏洞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在遵守代码分析错误的过程中,我将属性更改为具有私有设置程序.然后,我开始尝试进一步了解为什么.从一些研究中,MS说:

In the process of adhering to code analysis errors, I'm changing my properties to have private setters. Then I started trying to understand why a bit more. From some research, MS says this:

可写集合属性允许用户用完全不同的集合替换集合.

A writable collection property allows a user to replace the collection with a completely different collection.

此处的答案指出:

List<T>对象上添加公共设置器很危险.

Adding a public setter on a List<T> object is dangerous.

但是没有列出原因为何危险的原因.那就是我很好奇的部分.

But the reason why it's dangerous is not listed. And that's the part where I'm curious.

如果我们有此收藏集:

public List<Foo> Foos { get; set; }

为什么将二传手设为私人?显然,我们不希望客户端代码替换集合,,但是如果客户端可以删除每个元素,然后添加所需的内容,那有什么意义?这与完全替换收藏集不一样吗?遵循此代码分析规则如何提供价值?

Why make the setter private? Apparently we don't want client code to replace the collection, but if a client can remove every element, and then add whatever they want, what's the point? Is that not the same as replacing the collection entirely? How is value provided by following this code analysis rule?

推荐答案

不公开设置器可防止为集合分配值null的情况. null和没有任何值的集合之间是有区别的.考虑:

Not exposing the setter prevents a situation where the collection is assigned a value of null. There's a difference between null and a collection without any values. Consider:

for (var value in this.myCollection){ // do something

当没有值时(即有人在每个值上调用了Remove),则不会发生任何不好的情况.但是,当this.myCollection为空时,将抛出NullReferenceException.

When there are no values (i.e. someone has called Remove on every value), nothing bad happens. When this.myCollection is null, however, a NullReferenceException will be thrown.

代码分析假设您的代码在对其进行操作之前不会检查myCollection是否为空.

Code Analysis is making the assumption that your code doesn't check that myCollection is null before operating on it.

对于System.Collections.Concurrent中定义的线程安全集合类型,它可能也是一种额外的保护措施.想象一下某个线程试图通过覆盖整个集合来替换它.通过摆脱公共设置器,线程唯一的选择是调用线程安全的AddRemove方法.

It's probably also an additional safeguard for the thread-safe collection types defined in System.Collections.Concurrent. Imagine some thread trying to replace the entire collection by overwritting it. By getting rid of the public setter, the only option the thread has is to call the thread-safe Add and Remove methods.

这篇关于集合属性应该是只读的-漏洞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆