The <T> collection does not contain all the properties of the ICollection interface

The class Collection<T>implements several interfaces, one of which ICollection. The interface ICollectionhas 2 properties that are not implemented in Collection<T>.

In C #, I believe that you should implement all the methods and properties of an interface in a class that inherits it. So how is the class Collection<T>allowed to leave with it?

+4
source share
3 answers

This is called explicitly implementing the interface . You can make an element invisible from the outside if the reference to the object is not converted to an interface type.

Collection<T> ICollection , , #. , " " .

, .

var x = new Collection<int>();
object syncRoot = x.SyncRoot; //CS1061: Collection<int> does not contain a ....
ICollection collection = x;
syncRoot = collection.SyncRoot; //ok

, - . :

interface IFile
{
    void Save();
}
interface IDatabaseRecord
{
    void Save();
}

class Customer : IFile, IDatabaseRecord
{
    public void Save()
    {
        //what to do here?
    }
}

:

class Customer : IFile, IDatabaseRecord
{
    void IFile.Save() { }
    void IDatabaseRecord.Save() { }
}

, - , ( ).

+7

, , :

bool ICollection.IsSynchronized 
{
  get { return false; }
}

, , :

public bool IsSynchronized 
{
  get { return false; }
}

, , ICollection

var c = new Collection<double>();
var casted = (ICollection) c;
var isSync = casted.IsSynchronized;
+2

His uncle works for the frame, and everyone just looks the other way.

Pass a Collection<T>as ICollection, and you will see that it implements the entire interface ICollection.

+1
source

All Articles