本文主要是介绍泛型委托System.Func与System.Action,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Func<>是一个能接受多个参数和一个返回值的泛型委托,它能接受0个到4个输入参数, 其中 T1,T2,T3,T4 代表自定的输入类型,TResult为自定义的返回值。public delegate TResult Func<TResult>()
public delegate TResult Func<T1,TResult>(T1 arg1)
public delegate TResult Func<T1,T2, TResult>(T1 arg1,T2 arg2)
public delegate TResult Func<T1,T2, T3, TResult>(T1 arg1,T2 arg2,T3 arg3)
public delegate TResult Func<T1,T2, T3, ,T4, TResult>(T1 arg1,T2 arg2,T3 arg3,T4 arg4)
Action<>与Func<>十分相似,不同在于Action<>的返回值为void,Action能接受1~16个参数
public delegate void Action<T1>()
public delegate void Action<T1,T2>(T1 arg1,T2 arg2)
public delegate void Action<T1,T2, T3>(T1 arg1,T2 arg2, T3 arg3)
.............
public delegate void Action<T1,T2, T3, ,T4, ...... ,T16>(T1 arg1,T2 arg2,T3 arg3,T4 arg4,...... ,T16 arg16)
例子1:Action
using UnityEngine;
using System.Collections;
using System;
public class ActionTest : MonoBehaviour {
void Start () {
Action action = XXX;
action();
}
void XXX()
{
Debug.Log("100");
}
}
例子2: Action< T >
using UnityEngine;
using System.Collections;
using System;
public class ActionTest : MonoBehaviour {
void Start () {
Action< int > action = XXX;
action(10);
}
void XXX(int id)
{
Debug.Log("id:"+id);
}
}
例子3: Action< T1,T2 >
using UnityEngine;
using System.Collections;
using System;
public class ActionTest : MonoBehaviour {
void Start () {
Action< string,int > action = XXX;
action("jack",19);
}
void XXX(string name,int age)
{
Debug.Log("{0} is {1} years old.",name,age);
}
}
例子4:Func< TResult >
using UnityEngine;
using System.Collections;
using System;
public class ActionTest : MonoBehaviour {
void Start () {
Func< int > action = XXX;
action();
}
int XXX()
{
return 10;
}
}
例子5:Func< T,TResult >
using UnityEngine;
using System.Collections;
using System;
public class ActionTest : MonoBehaviour {
void Start () {
Func< string,int > action = CalStringLength;
action("jack");
}
int CalStringLength(string str)
{
return str.Length;
}
}
这篇关于泛型委托System.Func与System.Action的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!