C#之Action的实际应用例子

public class DemoAction
{
    public Action action;
    public Action<int> action1;
    public Action<int,string> action2;
    public Action<List<int>> action3;

    /// <summary>
    /// 不带参数
    /// </summary>
    public void ActionDemo()
    {
        if (action != null)
        {
            action();
        }
    }

    /// <summary>
    /// 带一个参数
    /// </summary>
    /// <param name="a"></param>
    public void ActionDemo(int a)
    {
        if (action1 != null)
        {
            action1(a);
        }
    }

    /// <summary>
    /// 带两个参数
    /// </summary>
    /// <param name="a"></param>
    /// <param name="str"></param>
    public void ActionDemo(int a,string str)
    {
        if (action2 != null)
        {
            action2(a,str);
        }
    }

    /// <summary>
    /// 带一个列表
    /// </summary>
    /// <param name="?"></param>
    public void ActionDemo(List<int> list){
        if (action3 != null)
        {
            action3(list);
        }
    }
}



public class CSharpDemo : MonoBehaviour {

    Action action;
    
    
    // Use this for initialization
	void Start () {

        DemoAction demo = new DemoAction();
        demo.action = TestAction;
        demo.action1 = TestAction;
        demo.action2 = TestAction;
        demo.action3 = TestAction;

        List<int> list = new List<int>(){10,20,30,40};
        demo.action();
        demo.action1(20);
        demo.action2(20, "rose_grils");
        demo.action3(list);

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


    /// <summary>
    /// 不带参数
    /// </summary>
    void TestAction(){
        Debug.LogError(" 不带参数");
    }

    /// <summary>
    /// 带一个参数
    /// </summary>
    /// <param name="a"></param>
    void TestAction(int a)
    {
        Debug.LogError("带一个参数 =  " + a);
    }

    /// <summary>
    /// 带2个参数
    /// </summary>
    /// <param name="a"></param>
    /// <param name="str"></param>
    void TestAction(int a, string str)
    {
        Debug.LogError("带2个参数a = " + a + "  str = " + str);
    }

    /// <summary>
    /// 带一个列表
    /// </summary>
    /// <param name="list"></param>
    void TestAction(List<int> list)
    {
        Debug.LogError("带一个列表");
        for (int i = 0; i < list.Count; i++)
        {
            Debug.LogError("i = " + list[i]);
        }
    }

}


 

运行结果如下图:

C#之Action的实际应用例子_第1张图片

你可能感兴趣的:(C#,action,委托)