ewefr

C#-delegate調用範例

張貼者: Tony 2011年10月20日 星期四

委派調用1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleAP
{
    class MulticastTester
    {
         delegate void Greeting();


        public static void main()
        {

            Greeting SayHello = new Greeting(SayHelloGo);
            Greeting SayHi = new Greeting(SayHiGo);
            Greeting SayHelloAndHi = SayHello + SayHi;
            Greeting SayBye = new Greeting(SayByeGo);

            SayHi();
            SayHello();
            SayHelloAndHi();

            SayHelloAndHi += SayBye;
            SayHelloAndHi += SayHello;
            SayHelloAndHi += SayHello;
            SayHelloAndHi();
            Console.WriteLine("-----------------------------");
            SayHelloAndHi -= SayHello;
            SayHelloAndHi -= SayHello;
            SayHelloAndHi();


            Console.ReadKey();
        }


        public static void SayHelloGo() {
            Console.WriteLine("Hello!");
        }

        public static void SayHiGo() {
            Console.WriteLine("Hi!");
        }

        public static void SayByeGo() {
            Console.WriteLine("Bye!");
        }

    }
}

委派調用2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleAP
{
    class delegateTest
    {
        public delegate int mydelegate(int i,int j);

        public static void Main()
        {
            mydelegate AddGo = new mydelegate(Add);
            Console.WriteLine("9+1=");
            Console.WriteLine(AddGo(9,1).ToString());

            mydelegate SubGo = new mydelegate(Sub);
            Console.WriteLine("9-1=");
            Console.WriteLine(SubGo(9, 1).ToString());


            Console.ReadKey();
        }

        public static int Add(int i,int j){
            return i + j;
        }

        public static int Sub(int i, int j) {
            return i - j;
        }

    }
}

0 意見

張貼留言

The Will Will Web

技術分享
MVP版主

重灌狂人

資訊分享

wowboxBlog

提供網頁設計相關資訊

KingKong Bruce記事

技術分享

C# Examples

csharp相關技術與範例

黑暗執行緒

技術分享
MVP版主

杨延成

技術分享
作者文章對於EF有詳細介紹

月光下的嘆息

工具分享
介紹許多好用的工具程式

Dot blogs

DotNet

格子樑/艾倫郭

技術分享
MVP版主