C# delegate 委托 event 事件

using System;

class Program
{
    static void Main(string[] args) {
        Teacher t = new Teacher();
        t.AskStudentDoSomething();
    }

}

public delegate void Something(string name);

public class Teacher
{
    public void AskStudentDoSomething() {
        Student student = new Student("Peter");
        Something s = new Something(A);
        student.DoSomething(s);
    }

    private void A(string name) {
        Console.WriteLine(name + " should go to buy some books.");
    }
}

public class Student
{
    private string name;

    public Student(string name) {
        this.name = name;
    }

    public void DoSomething(Something something) {
        // Console.WriteLine("should go to buy some books.");// 写死是不对的,应该在 Teacher 按需写内容,使用 delegate
        something(name);
    }

}

using System;

/*
event 和 delegate 的关系就好像字段和属性的关系;
event 会限制 delegate 不能够直接赋值操作,防止将委托替换掉,只能使用 += 和 -= 来绑定
或解除绑定;
event 还限定了delegate 只能在定义的类中被调用;
*/

class Program
{
    static void Main(string[] args) {
        Teacher t = new Teacher();
        t.askStudentDoSomething();
    }

}

public delegate void Something(string name);

public class Teacher
{

    public void askStudentDoSomething() {
        Student s = new Student("Peter");
        // 使用了 event 之后就不能直接给委托赋值 必须使用 += -= 来绑定或解除绑定
        s.something += new Something(A);
        // 使用了 event 之后就不能直接在 Student 外调用委托
        // s.something("Peter");
        s.Do();
    }

    private void A(string name) {
        Console.WriteLine(name + " should go to read more books.");
    }
}

public class Student
{

    private string name;

    public event Something something;

    public Student(string name) {
        this.name = name;
    }

    public void Do() {
        something(name);
    }

}

///
/// 
//class Program
//{
//  static void Main(string[] args) {
//      Teacher t = new Teacher();
//      t.askStudentDoSomething();
//  }

//}

//public delegate void Something(string name);

//public class Teacher
//{

//  public void askStudentDoSomething() {
//      Student s = new Student("Peter");
//      s.something = new Something(A);
//      s.Do();
//  }

//  private void A(string name) {
//      Console.WriteLine(name + " should go to read more books.");
//  }
//}

//public class Student
//{

//  private string name;

//  public Something something;

//  public Student(string name) {
//      this.name = name;
//  }

//  public void Do() {
//      something(name);
//  }

//}
///
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值