C#学习 [类型系统] 接口(15)

概念

只定义方法,不定义实现,从而隐藏内部的实现细节。

示例代码: 实现一个接口

public interface  ICar
{
    public string getColor();
}

public class Car: ICar
{
    public string getColor(){
        return "Red";
    }
}

实例代码:实现多个接口

public interface IChinaCar
{
    public string getColor();
}

public interface IUsaCar
{
    public int getWeight();
}

public class Car : IChinaCar, IUsaCar
{
    public string getColor()
    {
        return "Red";
    }

    public int getWeight()
    {
        return 1000;
    }
}

注意事项

  • 接口方法不能用public abstract等修饰。接口内不能有字段变量,构造函数。
  • 接口内可以定义属性(有get和set的方法)。如string color { get ; set ; }这种。
  • 实现接口时,必须和接口的格式一致。
  • 必须实现接口的所有方法。
posted @ 2024-10-30 10:05  huiy_小溪  阅读(14)  评论(0)    收藏  举报