我只是研究IReadOnlyList<T>
创建只读列表。但我认为它不是 100% 只读的。我无法从列表中添加/删除项目,但我仍然可以修改成员。
考虑这个例子。
class Program
{
static void Main(string[] args)
{
List<Test> list = new List<Test>();
list.Add(new Test() { MyProperty = 10 });
list.Add(new Test() { MyProperty = 20 });
IReadOnlyList<Test> myImmutableObj = list.AsReadOnly();
// I can modify the property which is part of read only list
myImmutableObj[0].MyProperty = 30;
}
}
public class Test
{
public int MyProperty { get; set; }
}
为了使其真正成为只读的,我必须将其MyProperty
设为只读。这是一个自定义类,可以修改该类。如果我的列表是具有 getter 和 setter 属性的内置 .net 类怎么办?我认为在这种情况下,我必须编写一个只允许读取值的 .net 类的包装器。
有没有办法使现有的类不可变?