1、 . . . . 实验二委托、事件与继承 一、实验目的 1. 掌握扩展函数的用法; 2. 掌握C#委托和事件的用法; 3. 掌握C#继承和多态概念; 4. 掌握常用接口的使用方法。 二、实验容 (实验过程中编写的程序复制到本文件中,下课整理后上交) 1. 编写一个静态类MyExtensions,扩展.NET Framework基本类型的功能。 1)定义一个扩展方法IsPalindrome,扩展string类的功能,来判断字符串是否为回文(指顺读和倒读容都一样的文本)。为提高程序效率,该方
2、法中不能直接调用Reverse方法。 2)定义一个扩展方法ReverseDigits,允许int将自己的值倒置,例如将整型1234调用ReverseDigits,返回结果为4321。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace experiment2 { staticclassMyExtensions { publicstaticbool IsPalind
3、rome(thisstring str)
{
for(int i=0;i 4、nt[10];//数组中元素的数量应该是可变的
for(int i=0;;i++)//注意
{
if (num == 0) // 1 ?
break;
a[i] = num % 10;
j++;
num /= 10;
}
for(int i=0;i 5、要强制转换成int
}
return Reverse_num;
}
}
classProgram
{
staticvoid Main(string[] args)
{
string str;
int a;
Console.Write("Enter a string: ");
str = Console.ReadLine();
Console.WriteLine("\""+str+"\""+(str.IsPalindrome()?" is ":" is not ")+"a p 6、alindrome");
Console.Write("Enter an integer: ");
a=int.Parse(Console.ReadLine());
Console.WriteLine("The reverse of "+a+" is "+a.ReverseDigits());
}
}
}
2. 应用委托和泛型集合类知识,完成以下程序。
程序框架:
源程序2:
using System;
using System.Collections.Generic;
using System.Linq;
usin 7、g System.Text;
using System.Threading.Tasks;
namespace experment2_2
{
classDelegates
{
//创建委托类型
publicdelegateboolNumberPredicate( int number );
staticvoid Main( string[] args )
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//生成委托实例
NumberPredicate evenPredicate = I 8、sEven;
//利用委托变量调用IsEven
Console.WriteLine( "Call IsEven using a delegate variable: {0}",evenPredicate(2));
//选出偶数
List< int > evenNumbers = FilterArray( numbers, evenPredicate );
//描述并输出
DisplayList( "Use IsEven to filter even numbers: ", evenNumbers ); //滤过
//选出素数并输出
Number 9、Predicate primePredicate = IsPrime;
List 10、t 11、
List 12、mber % 2 == 0 );
}
//判断是否素数
privatestaticbool IsPrime( int number )
{
bool flag=true;
if(number<=1)
returnfalse;
else
{
for(int i=2;i 13、
}
}
return flag;
}
//列表元素输出
privatestaticvoid DisplayList(string description, List 14、splayList_prime( string description, List< int > list )
{
Console.Write(description);
foreach(int number in list)
{
Console.Write(number+" ");
}
Console.WriteLine();
}
}
}
3. 模拟连锁反应事件
(1) 创建 C#控制台应用程序。
(2) 在程序中新建一个表示太阳的类Sun,在其中定义一个事件OnRise,一个成员 15、方法Rise,并在方法中引发事件。参考源代码如下(太阳只有一个,所以将其定义为静态类) :
public static class Sun {
public static event EventHandler OnRise;
public static void Rise() {
Console.WriteLine("太阳从升起!");
if (OnRise != null)
OnRise(null, null);
}
}
(3) 在程序中新建一个公鸡类 Cock ,在其中定义私有字段 _n 16、ame ,针对 Sun.OnRise 事件的处理方法 Sun_OnRise,事件 OnSing,以与引发该事件的方法 Sing;在类的构造函数中初始化字段,并将事件处理方法与事件相关联。
参考源代码如下(Sun_OnRise 方法中调用了 Sing 方法,表示太阳升起会使公鸡打鸣) :
public class Cock {
private string _name;
public Cock(string name) {
_name = name;
Sun.OnRise += new EventHandler(Sun 17、OnRise);
}
private void Sun_OnRise(object sender, EventArgs e)
{
Console.WriteLine("公鸡{0}:", _name);
Console.WriteLine("雄鸡一声天下白!");
this.Sing();
}
public event EventHandler OnSing;
public void Sing() {
Console.WriteLine("喔喔喔……");
18、
if (OnSing != null)
OnSing(this, null);
}
}
(4) 在程序中新建一个主人类 Host,在其中同样定义字段_name,起床事件 OnGetup ,起床方法 Getup (引发起床事件) ,养鸡方法 Foster ,以与 Cock.OnSing 事件的处理方法 c1_OnSing,并在 Foster 方法中与事件相关联。
参考源代码如下(c1_OnSing 方法中调用了 Getup 方法,表示公鸡打鸣会使主人起床) :
public class Host {
19、 private string _name;
public Host(string name) { _name = name; }
public event EventHandler OnGetup;
public void Getup() {
Console.WriteLine("日出而作……");
if (OnGetup != null)
OnGetup(this, null)
}
public void Foster(Cock c1)
{
20、 c1.OnSing += new EventHandler(c1_OnSing);
}
private void c1_OnSing(object sender, EventArgs e)
{
Console.WriteLine("主人{0}:", _name);
Console.WriteLine("闻鸡起舞!");
this.Getup();
}
}
(5) 参照 Cock 类和 Host 类中的代码,新建狗类 Dog 和猫类 Cat,在其中定义字段 _own 21、er 以记录其主人对象,定义 owner_OnGetup 方法以处理 Host.OnGetup 事件(主人起床时,输出狗叫声"汪汪"和猫叫声"喵喵";)通过属性 Owner 封装字段_owner,并在其 set 访问函数中关联事件和事件处理方法。
(6) 在程序主方法中依次创建鸡、主人、狗、猫对象,而后调用 Sun.Rise 方法,参考源代码如下:
static void Main() {
Cock cock1 = new Cock("花花");
Host host1 = new Host("祖逖");
Host1.Foster( 22、cock1);
Dog dog1 = new Dog("旺财");
dog1.Owner = host1;
Cat cat1 = new Cat("咪咪");
cat1.Owner = host1; Sun.Rise();
}
(7) 编译运行程序,看看"太阳升起"这一事件会引发怎样的连锁反应。
源程序 3:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Thr 23、eading.Tasks;
namespace experiment2_3
{
//(2)
publicstaticclassSun
{
publicstaticeventEventHandler OnRise; //EventHandler 为委托名
publicstaticvoid Rise()
{
Console.WriteLine("太阳从升起!");
if (OnRise != null)
OnRise(null, null);
}
}
//(3)
publiccl 24、assCock
{
privatestring _name;
public Cock(string name)
{
_name = name;
Sun.OnRise += newEventHandler(Sun_OnRise);
}
privatevoid Sun_OnRise(object sender, EventArgs e)
{
Console.WriteLine("公鸡{0}:", _name);
Console.WriteLine("雄鸡一声天下白!");
this.Sing 25、);
}
publiceventEventHandler OnSing;
publicvoid Sing()
{
Console.WriteLine("喔喔喔……");
if (OnSing != null)
OnSing(this, null);
}
}
//(4)
publicclassHost
{
privatestring _name;
public Host(string name) { _name = name; }
publiceventEventH 26、andler OnGetup;
publicvoid Getup() {
Console.WriteLine("日出而作……");
if (OnGetup != null)
OnGetup(this, null);
}
publicvoid Foster(Cock c1)
{
c1.OnSing += newEventHandler(c1_OnSing);
}
privatevoid c1_OnSing(object sender, EventArgs e)
27、 {
Console.WriteLine("主人{0}:", _name);
Console.WriteLine("闻鸡起舞!");
this.Getup();
}
}
//(5.Dog)
publicclassDog
{
privatestring _name;
privateHost _owner;
public Dog(string name)
{
_name = name;
}
publicHost Owner
{
get { returnth 28、is._owner; }
set
{
this._owner = value;
Owner.OnGetup += newEventHandler(owner_OnGetup);
}
}
privatevoid owner_OnGetup(object sender, EventArgs e)
{
Console.Write("狗 {0}:", _name);
Console.WriteLine("汪汪");
}
}
//(5.Cat 29、)
publicclassCat
{
privatestring _name;
privateHost _owner;
public Cat(string name)
{
_name = name;
}
publicHost Owner
{
get { returnthis._owner; }
set
{
this._owner = value;
Owner.OnGetup += newEventHandler(owner_O 30、nGetup);
}
}
privatevoid owner_OnGetup(object sender, EventArgs e)
{
Console.Write("猫 {0}:", _name);
Console.WriteLine("喵喵");
}
}
//(6)
classProgram
{
staticvoid Main(string[] args)
{
Cock cock1 = newCock("花花");
Host host1 = newHost( 31、"祖逖");
host1.Foster(cock1);
Dog dog1 = newDog("旺财");
dog1.Owner = host1;
Cat cat1 = newCat("咪咪");
cat1.Owner = host1;
Sun.Rise();
}
}
}
4. 练习接口的使用
1)Array类的Sort方法需要数组中的元素实现IComparable接口。简单类型如int等已实现了IComparable接口,所以可以排序。设计一个Person类,带有First 32、Name和LastName属性,带的Birthday属性(DateTime类型),使之实现IComparable接口,按LastName进行比较;如果LastName相同,就按FirstName进行比较。
2)如果Person对象的排序方式与上述不同,就可以自己创建一个类,实现IComparer接口,其中定义了方法Compare,它独立于要比较的类,因此需要两个参数进行比较。写个一PersonComparer类,继承IComparer,使得能够按Birthday进行排序。
3)写一个测试类,生成如下Person数组,调用Sort方法进行两种方式的排序。
newPerson[] {
ne 33、w Person { FirstName = “Damon”, Lastname = “Hill”, Birthday = new DateTime(1990, 5, 1) },
new Person { FirstName = “Niki”, Lastname = “Lauda” , Birthday = new DateTime(1995, 10, 4) },
new Person { FirstName = “Ayrton”, Lastname = “Senna” , Birthday = new DateTime(1992, 6, 23) },
new Person { Firs 34、tName = “Graham”, Lastname = “Hill” , Birthday = new DateTime(1994, 9, 15) }
源程序4:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Interface_4
{
public class Person : IComparable 35、blic string FirstName;
public string LastName;
public DateTime Birthday;
public Person() { }
public Person(string FirstName, string LastName, DateTime Birthday)
{
this.FirstName = FirstName;
this.LastName = LastName;
36、 this.Birthday = Birthday;
}
public int CompareTo(Person p)
{
if (this.LastNamepareTo(p.LastName) == 0)
{
return this.FirstNamepareTo(p.FirstName);
}
else
return this.LastNamepareTo(p.L 37、astName);
}
public override string ToString()
{
return "FirstName=" + FirstName + ", " + "LastName=" + LastName + ", " + "Birthday=" + Birthday;
}
}
class PersonComparer : Person,IComparer 38、Comparer()
{
this.Birthday = Birthday;
}
public int Compare(Person p1, Person p2)
{
return p1.BirthdaypareTo(p2.Birthday);
}
}
class Program
{
static void Main(string[] args) 39、
{
Person[] persons = new Person[] {
new Person { FirstName = "Damon", LastName = "Hill", Birthday = new DateTime(1990, 5, 1) },
new Person { FirstName = "Niki", LastName = "Lauda" , Birthday = new DateTime(1995, 10, 4) },
new Person { Fir 40、stName = "Ayrton", LastName = "Senna" , Birthday = new DateTime(1992, 6, 23) },
new Person { FirstName = "Graham", LastName = "Hill" , Birthday = new DateTime(1994, 9, 15) }
};
Console.WriteLine("Order by name:");
Array.Sort(persons);
41、 foreach (var p in persons)
Console.WriteLine(p);
Console.WriteLine("Order by Birthday:");
Array.Sort(persons, new PersonComparer());
foreach (var p in persons)
Console.WriteLine(p);
Console.ReadKey();
} 42、
}
}
5. 练习继承与多态
(1)在程序中新建一个电子收款机类POS,在其中定义一个保护字段_area,与其封装属性Area,用以表示收款机所在地区的代码。
(2)在程序中新建一个IPayable接口,为其定义一个表示支付Pay方法,方法原型为:
void Pay(decimal money, POS pos);
(3)在程序中新建一个银行卡类BankCard,在其中定义保护字段_account 和_savings,分别表示银行卡账号和余额;为其定义带参构造函数,以与用于查询、取款和存款的成员方法。参考源代码如下(其中Math.Round方法用于将金额舍入到小数点 43、后两位):
public BankCard(string account)
{ account = account;}
public virtual void Query () // 查询
{
Console.WriteLine ("银行卡{0}上余额为{1}”,_account, _savings);
}
public virtual void Deposit (decimal money) // 存款
{
_savings += money;
_savings = Math.Round(_savings, 2);
}
public virtual void Draw 44、 (decimal money) // 取款
{
if (_savings > money)
{
_savings-=money;
_savings = Math.Round(_savings, 2);
}
else
Console.WriteLine(“余额不足”);
(4)在程序中新建一个支付卡类PayableCard,它继承了 BankCard类和IPayable接口,并实现了接口的Pay方法:当卡上余额大于支付金额时,从余额中减去支付金额并输出消息“支付##X元”;否则输出信息“余额不足,无法进行支付”。
(5)从PayableCard派生出本地卡类LocalCar 45、d和通行卡类GlobalCard,二者均包含字段_area,用以表示支付卡的地区代码。GlobalCard还包含字段_rate,表示异地支付的手续费比例(简单起见,这里设为0.01)。在这两个类中重载基类的构造函数和Pay方法。当支付卡与所用P0S机的地区代码不同时,本地卡不支持异地支付,通行卡则需要扣除手续费。
(6)从PayableCard派生出信用卡类CreditCard,在其中定义字段_limit、_rate,以与只读属性Overdraw,分别表示透支额度、还款利率(可简单地设为0.01),以与目前欠款(余额为正时欠款为0,否则为余额的相反数)。在类中重载Pay、Query和Depo 46、sit方法,其中支付不能超过透支额度;查询时应输出信用卡的额度、欠款和余额;而存款时如果存在欠款,那么需要扣除存款利息。
(7)在程序主方法中使用如下代码来测试上述类型,并解释程序的输出结果。
static void Main()
{
POS pos1 = new POS(“010");
POS pos2 = new POS("021");
BankCard[] cards = new Card[4];
cards[0] = new BankCard("bj10000001") ;
cards [1] = new LocalCard ("bj90000009", “010”); 47、
cards [2] = new GlobalCard(“sh30000001”, “021”);
cards[3] = new CreditCard(“sh80000008", 10000);
for (int i = 0; i < cards.Length; i++)
{
cards[i]. Deposit(2200);
Console.WriteLine (" {0}支付前”, cards [i]);
cards[i].Query();
if (cards[i] is IPayable)
{
((IPayable)cards[i]).Pay(1000, pos1);
48、
((IPayable)cards[i]).Pay(1190, pos2);
}
Console .WriteLine (“ {0}支付后", cards[i]);
cards[i].Query();
Console.WriteLine();
}
}
源程序5:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace exercise_5
{
public c 49、lass POS
{
private string area;
public POS(string area)
{
this.area = area;
}
public string Area { get; set; }
}
public interface IPayable
{
void Pay(decimal money, POS pos);
}
class BankCard
{
50、
private string _account;
decimal _savings;
public BankCard(string account)
{
_account = account;
}
public virtual void Query() // 查询
{
Console.WriteLine("银行卡{0}上余额为{1}", _account, _savings);
}






