委托(delegate)

Code:
using System;
using System.Windows.Forms;
using System.IO;

class Set
{
    private Object[] items;
    public Set(Int32 numItems)
    {
        items = new Object[numItems];
        for (Int32 i = 0; i < numItems; i++)
            items[i] = i;
    }
    // Define a Feedback type.
    // NOTE: This type is nested within the Set class.
    public delegate void Feedback(
    Object value, Int32 item, Int32 numItems);

    public void ProcessItems(Feedback feedback)
    {
        for (Int32 item = 0; item < items.Length; item++)
        {
            if (feedback != null)
            {
                // If any callbacks are specified, call them.
                feedback(items[item], item + 1, items.Length);
            }
        }
    }
}

class App
{
    static void Main()
    {
        StaticCallbacks();
        InstanceCallbacks();
    }
    static void StaticCallbacks()
    {
        // Create a set with five items in it.
        Set setOfItems = new Set(5);
        // Process the items, but give no feedback.
        setOfItems.ProcessItems(null);
        Console.WriteLine();
        // Process the items, and give feedback to the console.
        setOfItems.ProcessItems(new Set.Feedback(App.FeedbackToConsole));
        Console.WriteLine();
        // Process the items, and give feedback to a message box.
        setOfItems.ProcessItems(new Set.Feedback(App.FeedbackToMsgBox));
        Console.WriteLine();
        // Process the items, and give feedback to the
        // console AND to a message box.
        Set.Feedback fb = null;
        fb += new Set.Feedback(App.FeedbackToConsole);
        fb += new Set.Feedback(App.FeedbackToMsgBox);
        setOfItems.ProcessItems(fb);
        Console.WriteLine();
    }
    static void FeedbackToConsole(
    Object value, Int32 item, Int32 numItems)
    {
        Console.WriteLine("Processing item {0} of {1}: {2}.",
        item, numItems, value);
    }

    static void FeedbackToMsgBox(
    Object value, Int32 item, Int32 numItems)
    {
        MessageBox.Show(String.Format("Processing item {0} of {1}: {2}.",
        item, numItems, value));
    }

    static void InstanceCallbacks()
    {
        // Create a set with five items in it.
        Set setOfItems = new Set(5);
        // Process the items, and give feedback to a file.
        App appobj = new App();
        setOfItems.ProcessItems(new Set.Feedback(appobj.FeedbackToFile));
        Console.WriteLine();
    }
    //Writing To File "Status"
    void FeedbackToFile(
    Object value, Int32 item, Int32 numItems)
    {
        StreamWriter sw = new StreamWriter("Status", true);
        sw.WriteLine("Processing item {0} of {1}: {2}.",
        item, numItems, value);
        sw.Close();
    }
}


输出:

(控制台显示,消息框弹出,写入文件)



Processing item 1 of 5: 0.
Processing item 2 of 5: 1.
Processing item 3 of 5: 2.
Processing item 4 of 5: 3.
Processing item 5 of 5: 4.



反射加委托:

using System;
using System.Reflection;
using System.IO;

// Here are some different delegate definitions.
delegate Object TwoInt32s(Int32 n1, Int32 n2);
delegate Object OneString(String s1);
class App
{
    static void Main(String[] args)
    {
        if (args.Length < 2)
        {
            String fileName =
            Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().CodeBase);
            Console.WriteLine("Usage:");
            Console.WriteLine("{0} delType methodName [Param1] [Param2]",
            fileName);
            Console.WriteLine(" where delType must be TwoInt32s or OneString");
            Console.WriteLine(" if delType is TwoInt32s, " +
            "methodName must be Add or Subtract");
            Console.WriteLine(" if delType is OneString, " +
            "methodName must be NumChars or Reverse");
            Console.WriteLine();
            Console.WriteLine("Examples:");
            Console.WriteLine(" {0} TwoInt32s Add 123 321", fileName);
            Console.WriteLine(" {0} TwoInt32s Subtract 123 321", fileName);
            Console.WriteLine(" {0} OneString NumChars \"Hello there\"",
            fileName);
            Console.WriteLine(" {0} OneString Reverse \"Hello there\"",
            fileName);
            Console.ReadKey();
            return;
        }
        Type delType = Type.GetType(args[0]);
        if (delType == null)
        {
            Console.WriteLine("Invalid delType argument: " + args[0]);
            return;
        }
        Delegate d;
        try
        {
            d = Delegate.CreateDelegate(delType, typeof(App), args[1]);
        }
        catch (ArgumentException)
        {
            Console.WriteLine("Invalid methodName argument: " + args[1]);
            return;
        }

        Object[] callbackArgs = new Object[args.Length - 2];
        if (d.GetType() == typeof(TwoInt32s))
        {
            try
            {
                for (Int32 a = 2; a < args.Length; a++)
                    callbackArgs[a - 2] = Int32.Parse(args[a]);
            }
            catch (FormatException)
            {
                Console.WriteLine("Parameters must be integers.");
                return;
            }
        }
        if (d.GetType() == typeof(OneString))
        {
            Array.Copy(args, 2, callbackArgs, 0, callbackArgs.Length);
        }
        try
        {
            Object result = d.DynamicInvoke(callbackArgs);
            Console.WriteLine("Result = " + result);
        }
        catch (TargetParameterCountException)
        {
            Console.WriteLine("Incorrect number of parameters specified.");
        }

        Console.ReadKey();
    }
    // This is the callback method that takes two Int32 parameters.
    static Object Add(Int32 n1, Int32 n2)
    {
        return n1 + n2;
    }
    static Object Subtract(Int32 n1, Int32 n2)
    {
        return n1 - n2;
    }
    // This is the callback method that takes one String parameter.
    static Object NumChars(String s1)
    {
        return s1.Length;
    }
    static Object Reverse(String s1)
    {
        Char[] chars = s1.ToCharArray();
        Array.Reverse(chars);
        return new String(chars);
    }
}

调试--启动选项-命令行参数 输入:TwoInt32s Add 111 222

输出:Result = 333

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值