如何确定 class 与属性(抽象和接口)的关系
How can I determine the relationship of a class to properties (Abstract and Interface)
根据阿米尔在 When to use an interface instead of an abstract class and vice versa?
When you derive an Abstract class, the relationship between the
derived class and the base class is 'is a' relationship. e.g., a Dog
is an Animal, a Sheep is an Animal which means that a Derived class is
inheriting some properties from the base class.
Whereas for implementation of interfaces, the relationship is "can
be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog
can be a race dog. Which means that you implement certain methods to
acquire something.
但是能力呢?例如,"A dog can bark"、"a cat can jump"、"a snake can slither",我将把它们放在抽象还是接口中?
如果你有一些共同的能力,比如移动,你可以有一个接口并让抽象 class 实现这些方法(如果动物是你唯一要使用的东西,那么你不会我相信通过拥有该界面真的可以获得很多)。如果您拥有仅适用于某些派生的 classes 的特定能力,请让他们实现该接口。
狗叫好像是一个派生class才有的能力,为什么不让那个派生class实现呢?将它抽象为 class 意味着所有动物都可以吠叫,但是如果狗是你唯一有能力的动物,那么再次让狗 class 实现一个带有树皮的接口似乎有点奇怪吠叫声。
旁注:接口不一定必须定义为 "can be" 关系。
做某事的能力可能最适合接口,除非您希望在未实现该方法的情况下提供一些默认行为。
请记住,C# 不支持继承多个 类,但支持实现多个接口。这允许一些灵活性。比如这样:
interface IBreathes()
{
void Breathe();
}
interface IMoveable()
{
void Move(int x, int y);
}
class Snake : Animal, IBreathes, IMoveable
{
void Breathe()
{
...
}
void Move(int x, int y)
{
...
}
}
对于上面的示例,使用抽象 类 会很好,但是对于大型、复杂的项目,解决单一继承问题可能会变得非常令人沮丧。
还有一件事需要考虑:您的实现 class 可以实现任意数量的接口,但您只能直接从一个 class 继承,无论是抽象的还是具体的。
简而言之:尽可能使用接口,必要时抽象 classes。
根据阿米尔在 When to use an interface instead of an abstract class and vice versa?
When you derive an Abstract class, the relationship between the derived class and the base class is 'is a' relationship. e.g., a Dog is an Animal, a Sheep is an Animal which means that a Derived class is inheriting some properties from the base class.
Whereas for implementation of interfaces, the relationship is "can be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog can be a race dog. Which means that you implement certain methods to acquire something.
但是能力呢?例如,"A dog can bark"、"a cat can jump"、"a snake can slither",我将把它们放在抽象还是接口中?
如果你有一些共同的能力,比如移动,你可以有一个接口并让抽象 class 实现这些方法(如果动物是你唯一要使用的东西,那么你不会我相信通过拥有该界面真的可以获得很多)。如果您拥有仅适用于某些派生的 classes 的特定能力,请让他们实现该接口。
狗叫好像是一个派生class才有的能力,为什么不让那个派生class实现呢?将它抽象为 class 意味着所有动物都可以吠叫,但是如果狗是你唯一有能力的动物,那么再次让狗 class 实现一个带有树皮的接口似乎有点奇怪吠叫声。
旁注:接口不一定必须定义为 "can be" 关系。
做某事的能力可能最适合接口,除非您希望在未实现该方法的情况下提供一些默认行为。
请记住,C# 不支持继承多个 类,但支持实现多个接口。这允许一些灵活性。比如这样:
interface IBreathes()
{
void Breathe();
}
interface IMoveable()
{
void Move(int x, int y);
}
class Snake : Animal, IBreathes, IMoveable
{
void Breathe()
{
...
}
void Move(int x, int y)
{
...
}
}
对于上面的示例,使用抽象 类 会很好,但是对于大型、复杂的项目,解决单一继承问题可能会变得非常令人沮丧。
还有一件事需要考虑:您的实现 class 可以实现任意数量的接口,但您只能直接从一个 class 继承,无论是抽象的还是具体的。 简而言之:尽可能使用接口,必要时抽象 classes。