欢迎加入Unity业内qq交流群:956187480
qq扫描二维码加群
1.Delegate,Action(常用)
#region 模块信息
// **********************************************************************
// Copyright (C) 2018 Blazors
// Please contact me if you have any questions
// File Name: GameDefine
// Author: romantic123fly
// WeChat||QQ: at853394528 || 853394528
// **********************************************************************
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public delegate void MyDelegate(string name);//定义委托
public delegate void Action();
public delegate void Action<T>(T obj);
public delegate void Action<T1, T2>(T1 arg1, T2 arg2);
public class ActionTest : MonoBehaviour {public MyDelegate myDelegate; //使用委托Action action;Action<string> action1;Action<string, int> action2;Action<string[]> action3;void Start(){myDelegate += DelegateFun;myDelegate("myDelegate");action += test1;//无参数action();action1 += test2;//一个参数action1("Test2");action2 += test3;//两个参数action2("Test3", 99);action3 += test4;//集合参数action3(new string[] { "charlies", "nancy", "alex", "jimmy", "selina" });}private void DelegateFun(string name){Debug.Log(name);}void test1(){Debug.Log("test1");}void test2(string str){Debug.Log(str);}void test3(string str,int num){Debug.Log(string.Format("{0} {1}", str, num));}void test4(string[] x){var result = from o in x where o.Contains("s")select o;foreach (string s in result.ToList()){Debug.Log(s);}}
}
2.Func,Predicate
Func可以传入多个参数,默认最后一个为返回值
Predicate只能接受一个传入参数,返回值为bool类型
#region 模块信息
// **********************************************************************
// Copyright (C) 2018 Blazors
// Please contact me if you have any questions
// File Name: GameDefine
// Author: romantic123fly
// WeChat||QQ: at853394528 || 853394528
// **********************************************************************
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;//有返回值的委托
public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T arg);
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);public class FuncTest : MonoBehaviour
{Func<int> func;Func<string, int> func1;Predicate<string[]> predicate;void Start(){func = XXX;Debug.Log(func());func1 = CallStringLength;Debug.Log(func1("sadasdads"));///bool Predicate<T>的用法///输入一个T类型的参数,返回值为bool类型predicate = func2;string[] _value = { "charlies", "nancy", "alex", "jimmy", "selina" };Debug.Log(predicate(_value));}private bool func2(string[] obj){var result = from p in objwhere p.Contains("s")select p;if (result.ToList().Count > 0){return true;}else{return false;}}int XXX(){return 10;}int CallStringLength(string str){return str.Length;}
}
欢迎加入Unity业内qq交流群:956187480
qq扫描二维码加群