using System;
namespace Interface
{
//类只能继承一个类,但是能继承多个接口
//既要继承类又要继承接口
//class 类:类 接口 接口
//接口是框架,一般情况下没有实际功能
//接口也是一个引用类型
interface IUSB
{
//接口中不能存在构造函数,接口中不许出现字段,
//接口中可以设置属性,但不能设置私有属性,接口中定义属性的情况较少
//接口中可以有方法,但是方法一般都没有方法体
float LifeTime { get; set; }
void ShowLifeTime(float a);
void SendMsg(string msg);
}
interface IUSBC:IUSB
{
}
//接口的使用:用类去实现继承该接口
//实现接口的类必须实现接口中的所有属性和方法
class ComputerMouse:IUSB
{
private string name;
public float LifeTime { get; set; }
public void ShowLifeTime(float a)
{
Console.WriteLine($"鼠标{name}的寿命为{LifeTime}");
}
public void SendMsg(string msg)
{
Console.WriteLine($"发送消息{msg}");
}
}
struct Keyborad:IUSB
{
public float LifeTime { get; set; }
public void ShowLifeTime(float a)
{
}
public void SendMsg(string msg)
{
}
}
public class Interface
{
}
}
using System;-------------------接口实例--------------------------------
namespace cInterfaceExample
{
interface IUSB
{
void ReadFile();
void WriteFile(string fileName);
}
interface IVGA
{
void ShowVideos();
}
class Device
{
private string name;
/// <summary>
/// 重量
/// </summary>
private float weight;
public Device(string name, float weight)
{
this.name = name;
this.weight = weight;
}
}
//类只能继承一个类
//但是可以实现多个接口
//在既继承类,又实现接口的情况下,类写在冒号[:]后的第一位
// class 类 : 类,接口,接口,接口,接口
class Computer : Device,IUSB,IVGA
{
public void ReadFile()
{
Console.WriteLine("计算机正在读取文件...");
}
public void WriteFile(string fileName)
{
Console.WriteLine($"计算机正在写入文件{fileName}...");
}
public void ShowVideos()
{
Console.WriteLine("计算机正在显示视频...");
}
public Computer(string name, float weight) : base(name, weight)
{
}
}
class Phone :Device, IUSB
{
public void ReadFile()
{
Console.WriteLine("手机正在读取文件...");
}
public void WriteFile(string fileName)
{
Console.WriteLine($"手机正在写入文件{fileName}...");
}
public Phone(string name, float weight) : base(name, weight)
{
}
}
class Program
{
static void Main(string[] args)
{
ReadFile(new Computer("华硕",100));
ReadFile(new Phone("iPhone",30));
}
static void ReadFile(IUSB usbDevice)
{
usbDevice.ReadFile();
}
}
}