Action<T> 與 Func<T> 泛型委派 Action<T> 與 Func<T> 泛型委派
  .NET       ez      2012-06-04

Action<T> 沒有回傳值的委派: 兩總寫法:

using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Action A1 = new Action(() =>
            {
                Console.WriteLine("Action1");
            });

            //or

            Action A2 = () =>
            {
                Console.WriteLine("Action2");
            };

            A1();
            A2();
        }
    }
}

多個值的委派:

using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Action A1 = () =>
            {
                Console.WriteLine("Action1");
            };
            Action<string> A2 = (x) =>
            {
                Console.Write("Action2");
                Console.WriteLine("\tx:" + x);
            };
            Action<string, string> A3 = (x, y) =>
            {
                Console.Write("Action3");
                Console.Write("\tx:" + x);
                Console.WriteLine("\ty:" + y);
            };
            Action<string, string, string> A4 = (x, y, z) =>
            {
                Console.Write("Action4");
                Console.Write("\tx:" + x);
                Console.Write("\ty:" + y);
                Console.WriteLine("\tz:" + z);
            };

            A1();
            A2("1");
            A3("1", "2");
            A4("1", "2", "3");
        }
    }
}

Func<T> 有回傳值的委派: 兩總寫法:

using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<bool> F1 = new Func<bool>(() =>
            {
                Console.WriteLine("Func1");
                return true;
            });

            //or

            Func<bool> F2 = () =>
            {
                Console.WriteLine("Func2");
                return true;
            };

            F1();
            F2();
        }
    }
}

多個值的委派:

using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string> F1 = () =>
            {
                return "Func1";
            };
            Func<string, string> F2 = (x) =>
            {
                return "Func2\tx:" + x;
            };
            Func<string, string, string> F3 = (x, y) =>
            {
                return "Func2\tx:" + x + "\ty:" + y;
            };
            Func<string, string, string, string> F4 = (x, y, z) =>
            {
                return "Func2\tx:" + x + "\ty:" + y + "\tz:" + z;
            };

            Console.WriteLine(F1());
            Console.WriteLine(F2("1"));
            Console.WriteLine(F3("1", "2"));
            Console.WriteLine(F4("1", "2", "3"));
        }
    }
}

標籤:   .NET

我要留言