天天看点

使用委派调用对象的方法

    委派即可以调用静态类方法,也可以调用对象方法。如下面的类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

private string model;

private int topSpeed;

public Car(string model, int topSpeed)

this.model = model;

this.topSpeed = topSpeed;

// 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

// create a delegate object that calls myPerson.NameAndAge()

// 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);

上一篇: 委派
下一篇: 队列Queue