2011-03-12 117 views
2

考虑到类冗余继承?

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> { } 

是ProductService多余的遗产?只需ServiceBase<Product>就够了?

这样

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(); 
} 

输出

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

回答

4

是的,它是多余的。

,您可以将其删除,并ProductService仍将实现IService<Product>

2

是的,从ServiceBase<Product>继承我只是做了测试就足够了。
但最简单的检查方法是查看派生类是否还包含由接口定义的方法/属性(通过IntelliSense)。

+0

智能感知诀窍是不是安全的,因为你也可以不实现接口 – digEmAll 2011-03-12 14:36:09

+0

@digEmAll定义相同的方法,但你不会得到一个错误/警告信息,告诉你,你有一个重复的方法,你应该使用'新'关键字,如果你打算重写它,或类似的东西......你知道我在说什么。在任何情况下,如果您确实想要检查/测试以获得问题的答案,请不要在派生类中使用另一种具有相同定义的方法。 :) – Kon 2011-03-12 14:38:33

+0

@Marc,苦多? – Kon 2011-03-12 14:41:45

2

这一切都取决于为什么 ...

它本身没有什么增加,也许除了一个名字。如果你有一个不喜欢泛型的序列化程序(除非被包装),或者如果你想添加/覆盖方法/属性,或者你只是想要一个固定的名字,这可能会很有用。

还要注意,可以使用扩展方法向这些类型(无继承)添加(-ish)方法,并且可以使用使用别名在单个文件中将其命名为

我个人不会继承它,除非我有一个原因。

+1

我不明白这是如何回答冗余问题。 – Kon 2011-03-12 14:35:41

+0

啊,我正在解释**整个类型**是多余的... – 2011-03-12 14:48:48

1

有一种情况是,在派生类中重新实现IFoo不是多余的:IFoo接口是在基类中显式实现的,并且您希望覆盖该实现。 请看下面的例子:

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(); 

    }   
}