Resticting访问方法对只读属性要求 [英] Resticting access to method calls on read-only properties

查看:228
本文介绍了Resticting访问方法对只读属性要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类定义了一个只读属性,有效地公开了私人领域,是这样的:

I have a class that defines a read-only property that effectively exposes a private field, something like this:

public class Container
{
    private List<int> _myList;

    public List<int> MyList
    {
    	get { return _myList;}
    }

    public Container() : base ()
    {
    	_myList = new List<int>();
    }

    // some method that need to access _myList
    public SomeMethod(int x)
    {
         _myList.Add(x);
    }
}

现在这是不可能的,为消费者直接管理我的财产,所以这样的代码aContainer.MyList =新名单();产生一个编译时错误。
然而,消费者是绝对自由调用各种关于他得到了参考方法,所以这是完全合法的代码

now it's impossible for the consumer to manage my property directly, so code like aContainer.MyList = new List(); generates a compile-time error. However, the consumer is absolutely free to call all sorts of methods on the reference he got, so this is perfectly valid code

Container c = new Container();  
Console.WriteLine(c.MyList.Count);  
c.MyList.Add(4);  
Console.WriteLine(c.MyList.Count);



哪种击败了整个只读的概念。

which kind of defeats the whole read-only concept.

有任何理智的解决办法,这将使我有一个真正的只读引用属性格式?

Is there any sane workaround that would enable me to have a real read-only reference propery?

PS我不能只返回列表的副本,因为这时用户会认为他做了所有必要的修改,但很可惜......他们将不复存在。

P.S. I cannot just return a copy of the list because then the user will think that he made all the changes necessary, but alas... they will be gone.

推荐答案

该参考只读 ,在实际的对象。即你不能替换另一个对象的引用。所以,如果你有打破它像这样的类:

The reference is "readonly", the the actual object. I.e. you can't replace the reference with another object. So if you have a class that breaks it like this:

public class Container
{
    private readonly  List<int> _myList;

    public List<int> MyList
    {
        get { return _myList;}
    }

    public Container() : base ()
    {
        _myList = new List<int>();
    }

    public void BreakReadOnly()
    {
        _myList = new List<int>();
    }
}



...那么它甚至不会编译。这是因为一个只读域不能与任何其他对象进行重新分配。在这种情况下 BreakReadOnly 将尝试分配一个新的列表。

…then it won't even compile. It's because a readonly field can't be reassigned with any other object. In this case BreakReadOnly will try to assign a new list.

如果你真的想它的只读集合,那么你可以做这样的:

If you really want a readonly collection of it then you can do it like this:

    public ReadOnlyCollection<int> MyList
    {
        get { return _myList.AsReadOnly(); }
    }



希望这有助于。

Hope this helps.

更新:不再使用的IEnumerable的。

Updated: Removed use of IEnumerable.

这篇关于Resticting访问方法对只读属性要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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