限制对只读属性的方法调用的访问 [英] Restricting access to method calls on read-only properties

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

问题描述

我有一个定义了只读属性的类,该属性有效地公开了一个私有字段,如下所示:

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 = new List();这样的代码生成编译时错误.但是,消费者绝对可以在获得的引用上自由调用各种方法,因此这是完全有效的代码

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?

P.S.我不能只返回列表的副本,因为这样用户会认为他做了所有必要的更改,但是a……它们将消失.

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.

推荐答案

参考文献为只读" ,实际对象.IE.您不能将引用替换为另一个对象.因此,如果您有一个像这样中断课程的课程:

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(); }
    }

希望这会有所帮助.

已更新:已删除对IEnumerable的使用.

Updated: Removed use of IEnumerable.

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

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