美文网首页
Action委托与Func委托

Action委托与Func委托

作者: 灰灰灰灰灰丶 | 来源:发表于2016-03-03 19:08 被阅读105次

    Action委托

    static void PrintString()
    {
    Console.WriteLine(“Action委托”);
    }
    Action a=PrintString; //Action委托是系统内置的一个委托类型,可以指向一个没有返回值没有参数的方法

    Action可以通过泛型去指定Action指向的方法的多个参数的类型,参数的类型和Action声明的参数类型一一对应:
    static void PrintInt(int x)
    {
    Console.WriteLine(x);
    }
    static void PrintIntString(int y,string str)
    {
    Console.WriteLine(y,“123”)
    }
    Action<int>=PrintInt;//定义了一个委托类型可以指向一个没有返回值,有一个int参数的方法。
    Action <int,string>=PrintIntString;//同上。指向一个没有返回值,有int和string两个参数的方法。

    Func委托

    是一个必须有返回值类型的委托。必须指定一个返回值类型。
    Func<参数类型(最多可以有16个参数),返回值类型> func=Test;
    先写参数,最后写返回值。 ·

    例1:static int Test(string str)
    {
    Console.WriteLine(str);
    return 100;
    }

    Func<string,int> func=Test; //指向参数为string类型,返回值为int类型的Test方法
    Console.WriteLine(func());

    例2:static int Test(int x,int y,int z)
    {
    return x+y+z;
    }

    Func<int,int,int,int> func=Test;//前三个int为参数,最后一个int为返回值

    相关文章

      网友评论

          本文标题:Action委托与Func委托

          本文链接:https://www.haomeiwen.com/subject/qzqokttx.html