我刚刚研究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; }
}
Run Code Online (Sandbox Code Playgroud)
为了使它真正只读,我必须MyProperty做为readonly.这是一个自定义类,可以修改类.如果我的列表是内置的.net类,它具有getter和setter属性怎么办?我认为在这种情况下我必须编写一个.net类的包装器,它只允许读取值.
有没有办法让现有的类不可变?