gpt4 book ai didi

c# - 如果您最终将 AsReadOnly 转换到 IEnumerable 中,它是否有意义?

转载 作者:行者123 更新时间:2023-11-30 13:43:27 29 4
gpt4 key购买 nike

我在 this 中看到了一些代码引起我注意的项目。

有一个简单的方法可以调用 List 上的 AsReadOnly。该方法没有对 ReadOnlyCollection 做任何事情,而是立即返回它并将其隐式转换为 IEnumerable。

如果您只需要一个 Enumerable,那么使用 AsReadOnly 有什么意义?

AsEnumerable 会是更好的选择吗?

private List<PaymentMethod> _paymentMethods = new List<PaymentMethod>();

public IEnumerable<PaymentMethod> PaymentMethods =>
_paymentMethods.AsReadOnly();

最佳答案

What is the point of using AsReadOnly if you only need an enumerable?

重点是AsReadOnly确保低信任度的敌对或错误调用者无法转换回可变集合。

Would AsEnumerable be a better option?

没有。试试这个:

List<int> list = new List<int>{ 10, 20, 30 };
...
IEnumerable<int> seq = list.AsEnumerable();
// Or (IEnumerable<int>)list, or whatever.
...
List<int> list2 = (List<int>)seq;
list2[0] = 40;

现在我们改变了list[0] .

但是AsReadOnly防止这种情况,因为只读包装器不能转换回 List<int> .

记住,AsEnumerable只是一种编写强制转换的视觉上更好的方式,并且作为引用转换的强制转换是引用转换。引用未更改,可以更改回其实际类型!

当然,具有完全信任的恶意或错误调用者可以任意破坏安全系统,因为完全信任意味着完全信任。只读集合维护对原始集合的引用,并且可以通过反射检索该引用。

此外,请记住只读意味着只读,而不是不变。围绕可变集合的只读包装器仍然可以观察更改;您只是无法通过只读包装器更改它

关于c# - 如果您最终将 AsReadOnly 转换到 IEnumerable 中,它是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57501296/

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