首页 > 开发 > 综合 > 正文

C#委托方法匿名的4种写法

2024-07-21 02:26:00
字体:
来源:转载
供稿:网友

using system;
using system.threading;

//不需要构造函数的委托对象
internal sealed class noconstructordelegateclass
{
    public static void callbackwithoutnewingadelegateobject()
    {
        threadpool.queueuserworkitem(someasynctask, 5);
    }

    private static void someasynctask(object o)
    {
        console.writeline(o);
    }
}

//不需要定义回调方法,生成一个一个静态委托字段,并在调用时实例化
internal sealed class nocallbackmethoddelegateclass
{
    public static void callbackwithoutnewingadelegateojbect()
    {
        threadpool.queueuserworkitem(delegate(object obj) { console.writeline(sm_name + obj); },5);
    }
}

//不需要指定回调方法的参数
internal sealed class nocallbackmethodandparametersdelegateclass
{
    public static void callbackwithoutnewingadelegateojbect()
    {
        threadpool.queueuserworkitem(delegate{ console.writeline("test"); }, 5);
    }
}

//不需要将局部变量人工封装到类中,即可将它们传给一个回调方法 自动生成辅助类
internal sealed class noenlocalvartoclassdelegateclass
{
    public static void usinglocalvariablesinthecallbackcode(int32 numtodo)
    {
        int32[] squares = new int32[numtodo];
        autoresetevent done = new autoresetevent(false);

        for (int32 n = 0; n < squares.length; n++)
        {
            threadpool.queueuserworkitem(delegate(object obj)
            {
                int32 num = (int32)obj;
               
                squares[num] = num * num;

                if (interlocked.decrement(ref numtodo) == 0)
                    done.set();
            }, n);
        }

        done.waitone();

        for (int32 n = 0; n < squares.length; n++)
        {
            console.writeline("index {0},square = [1]",n,squares[n]);
        }
    }

  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
  • 发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表