防止字典修改

TOP*_*KEK 0 c# dictionary readonly pass-by-reference

如何防止在课堂外修改字典项目?我必须将对象集合作为属性公开,但是每个人都可以使用我的对象完成所有操作.我试图用来ReadOnlyDictionary包装我的公共财产,但IntegerValue财产仍然可以从外面修改.

示例代码如下:

internal class MyRefClass
{
    public object ReferenceStrig;
    public int IntegerValue;

    public MyRefClass()
    {
     ReferenceStrig = "Initialized string";
        IntegerValue = 100;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var writableDict = new Dictionary<int, MyRefClass>();
        writableDict.Add(1,new MyRefClass());

        ReadOnlyDictionary<int, MyRefClass> dict = new ReadOnlyDictionary<int, MyRefClass>(writableDict);

    MyRefClass variable;
    dict.TryGetValue(1, out variable); #get an object from dictionary
    variable.IntegerValue = 0; #changing property of the object

    writableDict.TryGetValue(1, out variable); #get the same object once again
    #now property variable.IntegerValue == 0 instead of 100!
    }
}
Run Code Online (Sandbox Code Playgroud)

Sri*_*vel 5

如果要将对象公开给"客户端代码",但是您希望不修改该对象,则必须返回"不可变类型".以不可变类的形式或仅具有只读属性的接口.

这也意味着你的类型的所有属性和嵌套属性等也应该是"不可变的",否则它们仍然可以修改嵌套成员.换句话说,您公开的类型的对象图中的所有类型都必须是不可变的.

另一种选择是克隆对象并返回副本并忘记修改.但请确保您正在进行深拷贝而不是浅拷贝.浅拷贝遭受上述问题的困扰.