C#中接口的概念

Pet*_*erG 3 c# oop interface

我试图更好地理解C#和其他OOP语言中的接口.界面有什么作用?为什么需要?我知道c#和Java不允许多重继承.大多数书籍都说接口是绕过单继承限制并允许不同类具有通用功能的一种方法.接口只定义方法并强制类实现它们.为什么不让类本身定义和实现方法而不处理接口?例如:

4: using System;
5:
6: public interface IShape
7: {
8:    double Area();
9:    double Circumference();
10:   int Sides();
11: }
12:
13: public class Circle : IShape
14: {
15:    public int x;
16:    public int y;
17:    public double radius;
18:    private const float PI = 3.14159F;
19:
20: public double Area()
21: {
22:    double theArea;
23:    theArea = PI * radius * radius;
24:    return theArea;
25: }
.
.
.
Run Code Online (Sandbox Code Playgroud)

为什么Circle类不能定义和实现Area(),Circumference()和Sides()方法本身?如果square类继承了IShape,则Circumference()方法必须是未实现的.我对接口的理解是否有所作为?

Bat*_*rai 5

当你想说"我不在乎你怎么做,但这就是你需要完成的事情"时,接口就是为了.请参阅此链接以获取更多说明.