可以在课外修改私有成员吗? [英] Able to modify private member outside the class?

查看:65
本文介绍了可以在课外修改私有成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了可以在外部修改类的私有成员的情况.这是我的课:

I came across the situation where i am able to modify the private members of the class outside. Here is my class:

public class MyClass
{
    private List<string> _myClassMember = null;

    public MyClass()
    {
        _myClassMember = new List<string>();
    }

    public List<string> GetClassMembers()
    {
        return _myClassMember;
    }

    public void PrintMembers()
    {
        Console.WriteLine("No of items in member {0}", _myClassMember.Count.ToString());
    }
}

它的名字是这样的:

class Program
{
    static void Main(string[] args)
    {
        MyClass cls = new MyClass();
        cls.PrintMembers();
        IList<string> lst = cls.GetClassMembers();
        lst.Add("Item1");
        lst.Add("Item2");
        cls.PrintMembers();
    }
}

打印如下:

No of items in member 0
No of items in member 2

能够在外部更新私有成员是否正确?

is that correct being able to update the private member outside ?

推荐答案

是的.它只是私有的引用.如果您分享该参考.然后外部代码可以自由修改其内容.

Yes. It is just the reference that is private. If you share that reference. Then external code is free to modify its content.

如果您不希望外部代码修改内容,请改用不可变集合类.

If you do not want external code to modify the content, then use an immutable collection class instead.

虽然您可以修改由 myClassMember 引用的列表的内容,但您不能在类外部做的是更改 myClassMember 指向的列表.

Whilst you can modify the contents of the list referenced by myClassMember, what you can't do from outside the class is change the list that myClassMember points to.

这篇关于可以在课外修改私有成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆