Abstract getter with concrete setter in C #

I am trying to write an abstract base class for read-only collections that implement IList. Such a base class must implement set-indexer in order to throw away NotSupportedException, but leave get-indexer abstract. Does C # provide such a situation? Here is what I still have:

public abstract class ReadOnlyList : IList {

    public bool IsReadOnly { get { return true; } }

    public object this[int index] {
        get {
            // there is nothing to put here! Ideally it would be left abstract.
            throw new NotImplementedException();
        }
        set {
            throw new NotSupportedException("The collection is read-only.");
        }
    }

    // other members of IList ...
}

Ideally ReadOnlyList, the installer will be able to implement, but will leave an abstract formula. Is there any syntax that allows this?

+5
source share
7 answers

Transfer the work to protected members, which can then be marked as abstract or virtual, depending on the desired behavior. Try something like this:

 // implementor MUST override
 protected abstract object IndexerGet(int index);

 // implementor can override if he wants..
 protected virtual void IndexerSet(int index, object value) 
 {
   throw new NotSupportedException("The collection is read-only.");
 }

 public object this[int index] {
   get {
     return IndexerGet(index);
   }
   set {
     IndexerSet(index, value);
   }
 }
+8
source

, , . , , , .

+2

?

public abstract class ReadOnlyList : IList
    {

        public bool IsReadOnly { get { return true; } }

        public object this[int index]
        {
            get
            {
                // there is nothing to put here! Ideally it would be left abstract.
                throw new NotImplementedException();
            }
            private set
            {
                // your private implementation
            }
        }

        // other members of IList ...
    }
0

. , .

LSP : #?

0

, , IList?

IEnumerable.

0

- setter .

EDIT: jgauffin indicated that the setter comes from IList. Thus, you can have two options:

  • Implement IList privately and provide a public abstract getter for the indexer (not 100% if I can have two indexers).
  • Indexer getter will reference an abstract method such as GetItem.
-1
source

you don't need a setter

public abstract object this[int index] { get; }
-2
source

All Articles