开发者

Question About Interfaces

开发者 https://www.devze.com 2023-03-31 22:27 出处:网络
How is it possible for ReadOnlyCollection to implement IList?The latter requires implementation of the Add method, and the ReadOnlyCollection does not implement this.However, ReadOnlyCollection is con

How is it possible for ReadOnlyCollection to implement IList? The latter requires implementation of the Add method, and the ReadOnlyCollection does not implement this. However, ReadOnlyCollection is concrete and can be instantiated...

Edit

The following code will not compile on my machine:

static void Main(string[] args)
{
    List<string> people = new List<string>(){
        "Sidney",
        "Jim",
        "Bob"};

    ReadOnlyCollection<string> readOnlyPeople = new ReadOnlyCollection<string>(people);
    readOnlyPeople.Add("Frank");
}

The call to "Add" in the last statement is now underlined in b开发者_开发知识库lue in Visual Studio 2010.


It does implement Add, the implementation simply throws a NotSupportedException.

The implementation uses "explicit interface implementation", which is a way of implementing interfaces without directly exposing interface methods as public on the implementing class. It's most useful when you have a class that implements more than one interface that defines the same member (see the example at the link). Basically, it looks something like this:

public interface IList<T>
{
    int Add(object value);
    // and a whole bunch of other stuff...
}

public class ReadOnlyCollection<T> : IList<T>
{
    int IList<T>.Add(object value)
    {
        throw new NotSupportedException();
    }
}

Notice how the add method isn't public, so if you have an instance of ReadOnlyCollection<T>, you can't directly call Add on it. What you can do however, if you want to see the exception, is cast your instance to the interface:

ReadOnlyCollection<string> readOnlyPeople = new ReadOnlyCollection<string>(people);
((IList<string>)readonlyPeople).Add("Frank"); // <-- bang!

The other way you could achieve it is to declare your variable as an IList<T> directly:

IList<string> readOnlyPeople = new ReadOnlyCollection<string>(people);
readOnlyPeople.Add("Frank"); // <-- this should go 'bang!' too


It does implement the Add method, but the implementation of that method just throws a NotSupportedException.

0

精彩评论

暂无评论...
验证码 换一张
取 消