在C#中委托 [英] delegate in c#

查看:86
本文介绍了在C#中委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用委托人可以提出一些示例...
谢谢....

how to use delegate can anyone suggest some example...
Thank you....

推荐答案

委托与C ++中的函数指针大致相似.
委托声明定义了一种引用类型,该引用类型可用于封装具有特定签名的方法,并在以后使用.

使用方法

委托的类型安全要求您作为委托传递的函数具有与委托声明相同的签名.

有关使用委托的更多信息,请参见休闲程序.

Delegates are roughly similar to function pointers in C++.
A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature and can be used later.

How to use

The type safety of delegates requires the function you pass as a delegate to have the same signature as the delegate declaration.

See the fallowing program for more information on using delegates.

 namespace delegatess
{
    //Create a new category
    public delegate int MyDelegate(int x, int y);
    public class MyDelegateProgram
    {
        public static int FunAdd(int x, int y)
        {
            return x + y;
        }

        public static int FunMultiply(int x, int y)
        {
            return x * y;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //instance and initialization
            MyDelegate DelAdd = new MyDelegate(MyDelegateProgram.FunAdd);
            MyDelegate DelMul = new MyDelegate(MyDelegateProgram.FunMultiply);

            //invoking function using delegates
            Console.WriteLine("Addition : " + DelAdd(4, 5));
            Console.WriteLine("Multiplication : " + DelMul(4, 5));

            //array of Delegates-----------
            Console.WriteLine("Using Array of Delegate");

            MyDelegate[] arrDelegates;
            arrDelegates = new MyDelegate[2]; //size of delegate array
            arrDelegates[0] = new MyDelegate(MyDelegateProgram.FunAdd);
            arrDelegates[1] = new MyDelegate(MyDelegateProgram.FunMultiply);

            foreach (MyDelegate item in arrDelegates)
            {
                Console.WriteLine(item(4, 5));
            }
            Console.ReadKey();
        }
    }
}


希望这对


Hope this helps


Delegate定义了特定的签名.要调用委托对象,需要具有相同签名的方法.
请参阅以获取更多详细信息.这可能对您有帮助:代理示例
Delegate is defined with a specific signature. To invoke a delegate object,methods are required with the same signature.
See for more details.this may help you:Delegate example


这篇关于在C#中委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆