开发者

Redundant inheritance?

Consider that classes

public class Category { }
public class Product { }

public interface IService<T> { }
public class ServiceBase<T> : IService<T> { }

public class CategoryService : ServiceBase<Category> { }
public class ProductService : ServiceBase<Product>, IService<Product> { }

Is inh开发者_运维问答eritances of ProductService redundant? Just ServiceBase<Product> is enough?

I just made tests like this

static void Main(string[] args) {
    Console.WriteLine("CategoryService interfaces:");
    foreach(var item in typeof(CategoryService).GetInterfaces()) {
        Console.WriteLine(item.Name);
    }

    Console.WriteLine("ProductService interfaces:");
    foreach(var item in typeof(ProductService).GetInterfaces()) {
        Console.WriteLine(item.Name);
    }

    Console.ReadKey();
}

output

CategoryService interfaces:
IService`1
ProductService interfaces:
IService`1


Yes it's redundant.

You can remove it and ProductService will still implement IService<Product>


Yes, inheriting from ServiceBase<Product> is enough.
But the easiest way to check is to see if your derived class also contains methods/properties defined by the interface (via IntelliSense).


It all depends on why...

By itself it adds nothing, except perhaps a name. It might be useful if you have a serializer that doesn't like generics (unless wrapped), or if you want to add/override methods/attributes, or if you simply want a fixed name.

Note also that extension methods can be used to add(-ish) methods to such types (without inheritance), and that a using-alias can be used to name it in a single file.

Personally I wouldn't subclass it unless I had a reason.


There's a case when re-implementing IFoo in the derived class is not redundant: it's if the IFoo interface was implemented explicitly in the base class and you want to override the implementation. Look at this example:

interface IFoo
{
    void Foo();
}

class BaseFoo : IFoo
{
    void IFoo.Foo()    {
        Console.WriteLine("foo");
    }
}

// you can't ovverride the Foo() method without re-implementing the interface
class DerivedFoo : BaseFoo, IFoo 
{
    void IFoo.Foo()
    {
        Console.WriteLine("derived foo");
    }
}

class Example 
{

   static void Main() 
   {
        BaseFoo bf = new BaseFoo();
        ((IFoo)bf).Foo();

        bf = new DerivedFoo();
        ((IFoo)bf).Foo();

   }          
} 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜