class Program { public delegate void MyDelegate(); static void Main(string[] args) { MyDelegate myDelegate = new MyDelegate(Test.SayHello); myDelegate(); } } class Test { public static void SayHello() { Console.WriteLine("Hello Delegate!"); } }
4.1.2 说明
若使用静态方法,在向委托中传递方法名时,只需要用“类名.方法名”的形式
4.2 失实例二 将实例 1 中的静态方法改成实例方法
4.2.1 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Program { public delegate void MyDelegate(); static void Main(string[] args) { MyDelegate myDelegate = new MyDelegate(new Test().SayHello); myDelegate(); } } class Test { public void SayHello() { Console.WriteLine("Hello Delegate!"); } }
class Book:IComparable<Book> { //定义构造方法为图书名称和价格赋值 public Book(string name,double price) { Name = name; Price = price; } //定义图书名称属性 public string Name { get; set; } //定义图价格属性 public double Price { get; set; } //实现比较器中比较的方法 public int CompareTo(Book other) { return (int)(this.Price - other.Price); } //重写ToString方法,返回图书名称和价格 public override string ToString() { return Name + ":" + Price; } //图书信息排序 public static void BookSort(Book[] books) { Array.Sort(books); } }
class Program { //定义对图书信息排序的委托 public delegate void BookDelegate(Book[] books); static void Main(string[] args) { BookDelegate bookDelegate = new BookDelegate(Book.BookSort); Book[] book = new Book[3]; book[0] = new code_1.Book("计算机应用", 50); book[1] = new code_1.Book("C# 教程", 59); book[2] = new code_1.Book("VS2015应用", 49); bookDelegate(book); foreach(Book bk in book) { Console.WriteLine(bk); } } }