我需要使用
IReadOnlyList<T>
作为一个返回参数,因为它最符合我的需要,但正如您在下面的示例中所看到的,如果它不是真正的只读,您仍然可以修改它包装的列表。
using System.Collections.Generic;
using System.Collections.Immutable;
public class Test
{
public Test()
{
// return an IReadOnlyList that wraps a List, we can modify content
var list1 = GetList1();
if (list1 is List<Section> sections1) // can be true
{
sections1.Clear();
}
// return an IReadOnlyList that wraps an ImmutableArray, we cannot modify content
var list2 = GetList2();
if (list2 is List<Section> sections2) // never true
{
sections2.Clear();
}
}
public static IReadOnlyList<Section> GetList1()
{
return new List<Section> {new Section()};
}
public static IReadOnlyList<Section> GetList2()
{
return ImmutableArray.Create(new Section());
}
}
public struct Section
{
}
问题:
ImmutableArray<T>
看起来很棒,因为它是真正的只读,唯一的问题是我不想/不需要公开返回它
fully-featured class
这允许进行更改以生成副本。
因此,我坚持回去
IReadOnlyList<T>
因为它的意图很简单,但我需要修复可能可修改的列表问题。
问题:
正在返回一个
不可变数组<T>
作为一个
IReadOnlyList<T>
这是正确的方法吗?
如果没有,你能建议怎么做吗?