Are there any official ways to write an Immediately Invoked Function Expression?

后端 未结 6 1398
自闭症患者
自闭症患者 2021-02-04 02:21

Something like this:

var myObject = new MyClass()
{
    x = \" \".Select(y =>
    {
        //Do stuff..
        if (2 + 2 == 5)
            return \"I like c         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 02:37

    I'm surprised no one's mentioned this yet, but you could use the Lazy class:

    var myObject = new MyClass()
    {
        x = new Lazy(() =>
        {
            //Do stuff..
            if (2 + 2 == 5)
                return "I like cookies";
            else if (2 + 2 == 3)
                return "I like muffins";
            //More conditions...
            else
                return "I'm a bitter old man";
        }).Value // <-- Evaluate the function here
    };
    

    Alternatively, if you want to avoid having to specify the return type anywhere (as you do with new Lazy because constructors do not support type inference), you can implement a simple generic method like this:

    public static T Eval(Func func)
    {
        return func();
    }
    

    And then you can call like this:

    var myObject = new MyClass()
    {
        x = Eval(() =>
        {
            //Do stuff..
            if (2 + 2 == 5)
                return "I like cookies";
            else if (2 + 2 == 3)
                return "I like muffins";
            //More conditions...
            else
                return "I'm a bitter old man";
        })
    };
    

    Update: C#7 introduces local functions. These are not really IFFEs, but they may solve a variety of related issues. For example:

    var myObject = new MyClass()
    {
        x = GetX()
    };
    
    string GetX() {
        //Do stuff..
        if (2 + 2 == 5)
            return "I like cookies";
        else if (2 + 2 == 3)
            return "I like muffins";
        //More conditions...
        else
            return "I'm a bitter old man";
    }
    

    The key here is that GetX can be declared within the same method as myObject share the same scope as it.

提交回复
热议问题