.net框架笔记(六)之-------三
接上面的:
我在一次面试中:遇到过这样的一道题目:
猫叫了一声,主人被惊醒了,所有的老鼠都跑了.
现在用事件来写下,肯定有不妥之处,希望能够指教:
一:
1

2
//这把电话比做猫了,不好意思3
public class Phone4

{5
private int _height;6
private int _number;7

8
public int Number9

{10

get
{ return _number; }11

set
{ _number = value; }12
}13

14
public int Height15

{16

get
{ return _height; }17

set
{ _height = value; }18
}19

20
public event EventHandler Call;21

22
protected virtual void OnCall(EventArgs e)23

{24
if (Call != null)25

{26
Call(this,e);27
}28
}29
public void PhoneCall()30

{31
Console.WriteLine("电话响了,主人听到了");32
OnCall(new EventArgs());33
}34

35
36
}
1
//主人类2
public class Person3

{4
private string _name;5
private int _number;6

7
public string Name8

{9

get
{ return _name; }10

set
{ _name = value; }11
}12
13

14
public int Number15

{16

get
{ return _number; }17

set
{ _number = value; }18
}19

20
//要登记事件了,要不没人通知电话来了啊21
public Person(Phone phone)22

{23
phone.Call += new EventHandler(phone_Call);24
}25

26
public void phone_Call(object sender, EventArgs e)27

{28
Console.WriteLine("主人知道了,马上过去");29
}30

31

32
}
1
//老鼠类2
public class Mouse3

{4
private int _count;5

6
public int Count7

{8

get
{ return _count; }9

set
{ _count = value; }10
}11

12
public Mouse(Phone phone)13

{14
phone.Call += new EventHandler(phone_Call);15
}16

17
public void phone_Call(object sender, EventArgs e)18

{19
Console.WriteLine("电话响了,主人醒来了,老鼠逃跑了");20
}21
}
1
class Program2

{3
static void Main(string[] args)4

{5
Phone phone = new Phone();6
Person person = new Person(phone);7
Mouse mouse = new Mouse(phone);8

9
phone.PhoneCall();10
}11
}二:这个是自身触发
1
public class Phone2

{3
private int _height;4
private int _number;5

6
public int Number7

{8
get9

{10
return _number; 11
}12
set13

{14
if (_number !=value)15

{16
_number = value;17
OnCall(new EventArgs());18
}19
20
}21
}22

23
public int Height24

{25

get
{ return _height; }26

set
{ _height = value; }27
}28
public Phone()29

{ 30
this.Call += new EventHandler(Phone_Call);//先登记,后触发31
32
33
}34

35
public Phone(int number)36

{37
this.Call+=new EventHandler(Phone_Call);38
this.Number = number;39
40
41
}42

43
public void Phone_Call(object sender, EventArgs e)44

{45
Console.WriteLine("电话响了,号码为{0}",this.Number);46
}47

48
public event EventHandler Call;49

50
protected virtual void OnCall(EventArgs e)51

{52
if (Call != null)53

{54
Call(this, e);55
}56
}57
public void PhoneCall()58

{59
OnCall(new EventArgs());60
}61
62
63
}64
class Person65

{66
public Person(Phone phone)67

{68
phone.Call += new EventHandler(phone_Call);69
}70

71
public void phone_Call(object sender, EventArgs e)72

{73
Console.WriteLine("主人也登记了事件");74
}75
}76
class Program77

{78
static void Main(string[] args)79

{80
Phone phone = new Phone();81
Phone phone1 = new Phone(112222);82
//Person person = new Person(phone);83
Person person = new Person(phone);84
phone.PhoneCall();85
}86
}
希望能够指教.谢谢~

浙公网安备 33010602011771号