开发者

C# add event handler literal code block

Is it possible to add a literal code block as an event handler in C#? Something like:

Timer t = new Timer(10开发者_如何学运维00);
t.Elapsed += new ElapsedEventHandler({ Console.WriteLine("Tick"); });

You can do this in PowerShell, so I thought there might be some way to do this in C# too.


You can use a lambda expression (C# 3.0 and higher):

t.Elapsed += (sender, args) => Console.WriteLine("Tick");

or an anonymous method (C# 2.0 and higher):

// If you don't need the parameter values
t.Elapsed += delegate { Console.WriteLine("Tick"); };

// If you do need the parameter values
t.Elapsed += delegate(Object sender, ElapsedEventArgs args) {
    Console.WriteLine("Tick from {0}", sender); 
};


t.Elapsed += delegate(object sender, ElapsedEventArgs args)
             { 
                 Console.WriteLine["Tick"]; 
             });

Or, you could also use lambda syntax:

t.Elapsed += (sender, args) => { Console.WriteLine["Tick"]; };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜