程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> Delegates in C# - an introduction(轉:英文)

Delegates in C# - an introduction(轉:英文)

編輯:關於JSP

Introduction
I assume that most people who want to learn C# are C/C++ programmers. Thus I believe that they will be looking for features in C# which are analogous to some C/C++ feature they were quite fond of. And one of my favorite features about good old C was function pointers. Those of you who haven't used function pointers missed out on the fun. Well C# does have something that can be used where we used to use function pointers. Actually they do a lot more than function pointers used to do. They are called delegates. As is usual with me, I'll try and demonstrate the use of delegates through commented, sample programs that are small, simple and hopefully easy to understand.
Program 1
In this program we'll see how delegates are used to encapsulate a reference to a method in a delegate object. As you can see we can declare delegates in a namespace and thus delegates are shareable among classes. You can also see that we can associate a delegate variable with both static and instance member functions.
using System;
//declare our delegate type
public delegate void dgate();
class nish
{
    public static void Main()
    {
        test t1 = new test();
        //create a new delegate object and associate it
        //with the function abc in class test
        dgate d1 = new dgate(t1.abc);
        d1(); //call the delegate

        //now associate the delegate object with
        //the function xyz in class test
        d1 = new dgate(t1.xyz);
        d1(); //call the delegate

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved