How does List <T> not implement Add (object value)?

I think this is pretty stupid and I'm a little confused to ask this question, but I still could not find the answer:

I am considering a class List<T>that implements IList.

public class List<T> : IList

one of the methods included in Ilist,

int Add(object value)

I understand that List<T>I should not expose this method (type security ...), and it really is not. But how can this be? mustnt implement the whole interface?

+5
source share
6 answers

I believe that this (interface) method is implemented explicitly :

public class List<T> : IList
{
     int IList.Add( object value ) {this.Add((T)value);}
}

, Add( object ) . , List<T> IList.

+10

List<T> IList.Add(object value), . , :

IList list = new List<string>();
list.Add(new SqlDataReader()); // valid at compile time, will fail at runtime
+2

, IList.Add :

int IList.Add(object item)
{
    ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
    try
    {
        this.Add((T) item);
    }
    catch (InvalidCastException)
    {
        ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
    }
    return (this.Count - 1);
}

, T, .

+2

, IList, .

List<int> l = new List<int>();
IList il = (IList)l;
il.Add(something);
+1

, , :

List<int> lst = new List<int>();
((IList)lst).Add("banana");

, runtime, ArgumentException.

+1

, List<T> IList , , .

, , , , .

, , , , .

, IList.Add :

, -1 , .

, :

int IList.Add(object value)
{
    if (value is T)
    {
        Add((T)value);
        return Count - 1;
    }

    return -1;
}

This is just an assumption, of course. (If you really want to know for sure, you can always use a Reflector .) This may be a little different; for example, it can generate NotSupportedException, which is often done for incomplete interface implementations, such as an ReadOnlyCollection<T>implementation IList<T>. But since the above meets the documented requirements IList.Add, I suspect this is close to the real thing.

+1
source

All Articles