How should I use properties when dealing with read-only List members

后端 未结 7 1496
栀梦
栀梦 2020-12-01 08:26

When I want to make a value type read-only outside of my class I do this:

public class myClassInt
{
    private int m_i;
    public int i {
        get { ret         


        
7条回答
  •  佛祖请我去吃肉
    2020-12-01 09:23

    public class MyClassList
    {
        private List _lst = new List() { 1, 2, 3 };
    
        public IEnumerable ListEnumerator
        {
            get { return _lst.AsReadOnly(); }
        }
    
    }
    

    To check it

        MyClassList  myClassList = new MyClassList();
        var lst= (IList)myClassList.ListEnumerator  ;
        lst.Add(4); //At this point ypu will get exception Collection is read-only.
    

提交回复
热议问题