如何让班级真正永恒?班级

由网友(阑珊了春事)分享简介:我只是看着 IReadOnlyList< T> 以创建只读列表。但我认为这不是100%只读。我不能添加/删除列表中的项目,但我仍然可以修改的成员。 I just looked into IReadOnlyList to create readonly list. But I think it is...

我只是看着 IReadOnlyList< T> 以创建只读列表。但我认为这不是100%只读。我不能添加/删除列表中的项目,但我仍然可以修改的成员。

I just looked into IReadOnlyList<T> to create readonly list. But I think it is not 100% readonly. I can not add/remove the item from the list but I can still modify the members.

考虑这个例子。

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的为只读。这是一个自定义类,它是可以修改的类。如果我的名单里面有两个吸气和放大器内置.NET类的东西; setter属性?我认为,在这种情况下,我必须编写.NET类,只允许读值的包装。

To make it truly readonly I have to make MyProperty as readonly. This is a custom class, it's possible to modify the class. What if my list is of inbuilt .net class which has both getter & setter properties? I think in that case I have to write a wrapper of that .net class which only allows reading the value.

有没有什么办法让现有的类不可变的?

Is there any way to make the existing classes immutable?

推荐答案

一个真正的不可变类是指其属性和字段都为只读。这个定义是递归的包含在这一类的字段和属性的所有类也必须是只读的。你只读列表并非真正一成不变的,因为列表中的内容并不像你说的,你可以修改它们,因为一成不变的。在列表中的各个项目都必须只读,以及对 IReadOnlyList&LT; T&GT; 来真正成为不可改变

A truly immutable class is one whose properties and fields are all read-only. This definition is recursive in that all classes contained within this class's fields and properties must ALSO be read only. Your read-only list is not truly immutable, because the contents of the list are NOT immutable since as you said you can modify them. The individual items in the list would have to be read-only as well for the IReadOnlyList<T> to truly be immutable.

阅读全文

相关推荐

最新文章