How to call anonymous function in C#?

后端 未结 2 1083
感动是毒
感动是毒 2020-12-24 02:53

I am interested if it\'s possible using C# to write a code analogous to this Javascript one:

var v = (function()
{
    return \"some value\";
})()

相关标签:
2条回答
  • 2020-12-24 03:22

    Here's how you could then utilize such a construct to enclose context - closure-

    Control.Click += new Func<string, EventHandler>((x) =>
    new System.EventHandler(delegate(object sender, EventArgs e)
    {
    
    }))(valueForX);
    
    0 讨论(0)
  • 2020-12-24 03:31

    Yes, but C# is statically-typed, so you need to specify a delegate type.

    For example, using the constructor syntax:

    var v = new Func<string>(() =>
    {
        return "some value";
    })();
    
    // shorter version
    var v = new Func<string>(() => "some value")();
    

    ... or the cast syntax, which can get messy with too many parentheses :)

    var v = ((Func<string>) (() =>
    {
        return "some value";
    }))();
    
    // shorter version
    var v = ((Func<string>)(() => "some value"))();
    
    0 讨论(0)
提交回复
热议问题