孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

    委派即可以调用静态类方法,也可以调用对象方法。如下面的类Person定义了两个私有域来存储一个人的名字和年龄

 

1 public class Person
2 {
3
4 // declare two private fields
5   private string name;
6 private int age;
7
8 // define a constructor
9 public Person(string name, int age)
10 {
11 this.name = name;
12 this.age = age;
13 }
14
15 // define a method that returns a string containing
16 // the person's name and age
17 public string NameAndAge()
18 {
19 return(name + " is " + age + " years old");
20 }
21
22 }

接着在Main方法中创建Person对象

 

Person myPerson = new Person("Jason Price", 32);

然后创建委托类并调用

 

DelegateDescription myDelegateDescription =
new DelegateDescription(myPerson.NameAndAge);

// call myPerson.NameAndAge() through myDelegateDescription
string personDescription = myDelegateDescription();
Console.WriteLine(
"personDescription = " + personDescription);

完整代码:

/*
Example12_3.cs illustrates the use of a delegate
that calls object methods
*/

using System;


// declare the DelegateCalculation delegate class
public delegate string DelegateDescription();


// declare the Person class
public class Person
{

// declare two private fields
private string name;
private int age;

// define a constructor
public Person(string name, int age)
{
this.name = name;
this.age = age;
}

// define a method that returns a string containing
// the person's name and age
public string NameAndAge()
{
return(name + " is " + age + " years old");
}

}


// declare the Car class
public class Car
{

// declare two private fields
private string model;
private int topSpeed;

// define a constructor
public Car(string model, int topSpeed)
{
this.model = model;
this.topSpeed = topSpeed;
}

// define a method that returns a string containing
// the car's model and top speed
public string MakeAndTopSpeed()
{
return("The top speed of the " + model + " is " +
topSpeed
+ " mph");
}

}


class Example12_3
{

public static void Main()
{

// create a Person object named myPerson
Person myPerson = new Person("Jason Price", 32);

// create a delegate object that calls myPerson.NameAndAge()
DelegateDescription myDelegateDescription =
new DelegateDescription(myPerson.NameAndAge);

// call myPerson.NameAndAge() through myDelegateDescription
string personDescription = myDelegateDescription();
Console.WriteLine(
"personDescription = " + personDescription);

// create a Car object named myCar
Car myCar = new Car("MR2", 140);

// set myDelegateDescription to call myCar.MakeAndTopSpeed()
myDelegateDescription =
new DelegateDescription(myCar.MakeAndTopSpeed);

// call myCar.MakeAndTopSpeed() through myDelegateDescription
string carDescription = myDelegateDescription();
Console.WriteLine(
"carDescription = " + carDescription);

}

}
posted on 2011-05-07 20:03  孤独的猫  阅读(582)  评论(1编辑  收藏  举报