这篇文章主要介绍了C#委托与事件原理及实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

委托:个人在这里理解 委托就是 定义一个引用,一个可以记录函数指针的引用。

public delegate void GreetingDelegate(int param);

事件:就是基于委托定义的。

public event GreetingDelegate payxx;

其实这里的事件payxx 就差不多和string 一样可,只不过是存函数指针的变量。

这里上一个例子代码:


using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class basetest : MonoBehaviour
{

  public GameObject panel;
  private bool isclick = false;
  public delegate void GreetingDelegate(int param);
  public event GreetingDelegate payxx;
  // Use this for initialization
  void Start()
  {

  }

  // Update is called once per frame
  void Update()
  {

  }
  void OnMouseOver()
  {
    if (Input.GetMouseButtonDown(0))
    { //左键点击
      Debug.LogError("你点击了NPC");
      //playRenwu();
    }

  }
  public void pay() {
    Debug.LogError("触发了委托");
  }

  void playRenwu(bool isnotclick)
  {
    Debug.LogError("开始NPC任务");
    panel.gameObject.SetActive(isnotclick);
  }


  //protected virtual void Onpayxxxxx(int param)
  //{
  //  if (payxx != null)
  //  {
  //    Debug.LogError("委托的事件触发了");
  //    payxx(param);
  //  }
  //  else
  //  {
  //    Debug.LogError("委托的事件没触发");
  //  }

  /