今日继续我的C#学习之路,今日学习接口、委托、事件,文章从实践出发学习这三个设计理念,并提供完整源码
1、接口(多重继承):
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ipoint_YZH
{
internal class Program
{
static void Main(string[] args)
{
//应用接口的派生类Point实例化一个新的对象并进行初始化赋值
Point p = new Point(5,30);
Console.WriteLine("创建的点坐标是:x={0},y={1}\n",p.x,p.y);
Console.ReadLine();
}
public interface IPoint
{
int x { get; set; }//定义属性成员x,他含有读写的抽象访问
int y { get; set; }//定义属性成员y,他含有读写的抽象访问
}
class Point:IPoint
{
//定义俩个类内部访问的私有成员变量
private int px;
private int py;
//构造函数实现类初始化,为私有变量赋值
public Point (int x,int y)
{
px = x;
py = y;
}
//接口属性x实现
public int x
{
get { return px; }//实现读访问
set { px = value; }//实现写访问
}
//接口属性y实现
public int y
{
get { return py; }//实现读访问
set { py = value; }//实现写访问
}
}
}
}
运行结果:
2、委托(方法的代理/函数指针):
修改后的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Weituo
{
internal class Program
{
public delegate int myDelegateHandler(int a,int b);
public class A
{
//静态的处理方法,返回俩数相加之和
public static int M1(int a, int b)
{
int c = a + b;
return c;
}
}
public class B
{
static void Main(string[] args)
{
//实例一个委托
myDelegateHandler mdh = new myDelegateHandler(A.M1);
//调用委托
int sum = mdh(1, 2);
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
}
运行结果:
3、事件:
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace shijian_reshuiqi
{
internal class Program
{
static void Main(string[] args)
{
Heater heater = new Heater();//创建热水器对象heater
Alarm alarm = new Alarm();//创建报警器对象alarm
heater.BoilEvent += alarm.MakeAlert;//给alarm类的MakeAlert方法订阅事件
heater.BoilEvent += Display.ShowMsg;//给Display类的 ShowMsg静态方法订阅事件
heater.BoilWater();//烧水
Console.ReadLine();
}
//Heater热水器类
public class Heater
{
private int temperature;//声明表面当前水温字段
public delegate void BoilHandler(int param);//声明关于事件的委托
public event BoilHandler BoilEvent;//声明水要烧开的事件
public void BoilWater()//烧水的方法
{
for (int i=0;i<=100;i++)//水温超过96,引发事件BoilEvent
{
temperature = i;
if(temperature>96)
{
if(BoilEvent!=null)
{
BoilEvent(temperature);//调用所有订阅对象的方法
}
}
}
}
}
public class Alarm //定义Alarm警报
{
public void MakeAlert(int param)
{
Console.WriteLine("提示:水已经{0}度了", param);
}
}
public class Display//显示水温的类
{
public static void ShowMsg(int param)
{
Console.WriteLine("Display:s水快烧开了,当前温度:{0}度",param);
}
}
}
}