用C#中的Example进行委托

In C#, delegates are used to reference a method of a class. It’s almost similar to the function pointer in C and C++. Using a delegate we can encapsulate to a method of the class inside an object of the delegate.

在C#中, 委托用于引用类的方法。 它几乎类似于C和C ++中的函数指针。 使用委托我们可以封装到类的方法,该委托的对象的内部。

We can understand delegates by giving an example of a function call with or without a delegate.

我们可以通过给一个函数调用的例子有或没有委托理解代表

调用没有委托的方法 (Call a method without delegate)

using System;
using System.Collections;

class Sample
{
    public void fun()
    {
        Console.WriteLine("Call a Function without delegate");
    }
}

class Program
{
    static void Main()
    {
        Sample S = new Sample();

        S.fun();
    }
}

Output

输出量

    Call a Function without delegate

使用委托调用方法 (Call a method using delegate)

We can call a method using delegate also. Here, we need to use delegate keyword.

我们也可以使用委托来调用方法。 在这里,我们需要使用委托关键字。

Syntax:

句法:

 delegate return_type <delegate_name>([perameters]);

Here,

这里,

  • return_type - matches return type of the function.

    return_type-匹配函数的返回类型。

  • delegate_name - is an identifier that is user-defined delegate name.

    proxy_name-是用户定义的代理名称的标识符。

  • parameters - that define parameters passed in function.

    参数 -定义函数中传递的参数。

使用委托调用静态方法 (Call a Static method using delegate)

using System;
using System.Collections;

public delegate void myDelegates();
class Sample
{
    public static void fun()
    {
        Console.WriteLine("Call a static function using delegate");
    }
}

class Program
{
    static void Main()
    {
        myDelegates del = new myDelegates(Sample.fun);
        del();
    }
}

Output

输出量

    Call a static function using delegate


翻译自: https://www.includehelp.com/dot-net/delegates-with-example-in-c-sharp.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值