简体   繁体   中英

C# implementing interfaces with generic type overrides

To simplify my question, I'm using IList and IList<T> as the example. Since IList declared a method Add(object value) and IList<T> declared a method Add(T value) . My new class has to have two methods for implementation.

class myList<T> : IList<T>, IList
{
  public void IList.Add(object value)
  {
    this.Add(value as T);
  }
  public void Add(T value)
  {...}
}

Is it possible to avoid such "meaningless" replication?

The IList collection stores object instances, but IList<T> stores specific type instances. The Add methods has different signatures for IList and IList<T> interfaces. Therefore you need to declare both methods.

No you can't avoid this. Because this would violate the principle of interfaces. Think about a client program which just works with IList. This program want to use your class now, which works of course, because you implement IList. So he calls the Method:

public void IList.Add(object value)
{
  this.Add(value as T);
}

What should happen now, if you wouldn't implement this? Sure you can call Add<T> instead, but if there are many classes which implement IList and you call Add-Method on an IList interface to use polymorphism under the hood this would not work anymore.

C# is strict here for good reason, same as any other language with Interface Concept I know.

Maybe you should avoid implementing non generic IList because it violates SOLID and more precisely Liskov substitution principle. It's a legacy interface from .Net 1 when generics where not available. Well if you are dealing with legacy code, it can be necessary.

If you have to implement IList , has stated by Hans, use an implementation that will fail fast : throw an exception when the provided object is not allowed in your list.

void IList.Add(object value)
{
  this.Add((T)value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM