C# How to make public getters and setters and private methods for a collection?

后端 未结 4 1513
谎友^
谎友^ 2021-02-04 21:50

I\'d like to have a class \"A\" with a (for example) SortedList collection \"SrtdLst\" property, and inside this class \"A\" allow the addition or subtraction of \"SrtdLst\" ite

4条回答
  •  离开以前
    2021-02-04 22:31

    Just make the list private, and expose it as an indexer:

    class A {
    
       private SortedList _list;
    
       public A() {
          _list = new SortedList()
       }
    
       public string this[string key] {
          get {
             return _list[key];
          }
          set {
             _list[key] = value;
          }
       }
    
    }
    

    Now you can only access the items using the index:

    a["KeyA"] = "ValueBBB";
    

    However, as the indexer of the list allows creation of new items, you would have to add code in the indexer to prevent that if you don't want that do be possible.

提交回复
热议问题