zoukankan      html  css  js  c++  java
  • 事件对委托的限制体现

    区别:

    1.委托可以把一个方法作为参数代入另一个方法。
    2.委托是类型,事件是对象。
    3.事件是委托的一个修饰符,加了event(事件)修饰之后,委托就被限制了。

    总结:

    事件与委托最主要的区别是事件不能在外部调用,但可以通过+=或-=进行注册,他只能注册自己内部的方法到事件上。
    另外,外界也不能主动地触发一个事件。事件只能add、remove自己,不能赋值。

    如果委托变量为私有,则外部不能注册;如果为公有,则外部又可以调用,破坏了封装,所以就定义一个event进行限制是最合适的.

    委托和事件就相当于字段和属性

     1 using UnityEngine;
     2 using System.Collections;
     3 
     4 public delegate void DelegateEventHandler();
     5 
     6 public class Test : MonoBehaviour {
     7 
     8     //不用event对委托进行限制
     9     public DelegateEventHandler OnMyDelegate;
    10 
    11     //使用event对委托进行限制
    12     public static event DelegateEventHandler OnDelegate;
    13 
    14     void Start () {
    15          new MyClass();
    16         OnDelegate();
    17     }
    18 }
    19 
    20 public class MyClass {
    21 
    22     public MyClass() {
    23         //这种情况就会报错
    24         Test test = new Test();
    25         test.OnMyDelegate();
    26 
    27         //破坏封装
    28         test.OnMyDelegate = B;
    29         test.OnMyDelegate();
    30 
    31         //正确使用方法
    32         Test.OnDelegate += B;
    33     }
    34 
    35     void B() {
    36         Debug.Log("回调方法");
    37     }
    38 }

     

  • 相关阅读:
    Python基础篇 -- 列表
    Python基础篇 -- 字符串
    Python基础篇 -- if while 语句
    Python基础篇 -- 运算符和编码
    Python 入门基础
    Docker知识收藏
    秒表
    Emac
    Android开发
    shell 小工具
  • 原文地址:https://www.cnblogs.com/AaronBlogs/p/6832910.html
Copyright © 2011-2022 走看看