使用串联Lambda函数作为参数

时间:2019-07-10 03:10:31

标签: c# unity3d

我有选择地在Unity编辑器中根据为给定组件选择的选项显示一些内容,这将在显示当前组件上选择的选项的摘要时使用。

我如何使内联函数返回一个字符串,我希望该函数内联,因为会有很多这样的功能,它们仅在使用它们的行中有用。

我提供了一个代码段,可以阐明我要做什么。

我在c ++和JavaScript中使用过像这样的lambda函数,但在c#中却没有,我试图找到在C#中如何使用它们的答案。

var script = target as ButtonManager;//get reference to this Component 

EditorGUILayout.LabelField("Your current Interactive configuration", 
            "Parent: " + script.sceneParent.name + "\n",
            "Popup? " + ()=>{ if (script.isPopup) { return "Popup" } else { return "Change Scene"} }
            + "\n"
            );

编辑: 我可以使用三元运算符来解决此问题,但我很好奇它如何与lambda函数一起使用

3 个答案:

答案 0 :(得分:2)

要在字符串连接中使用委托内联,您需要根据匿名方法创建一个新的Func<string>并执行它:

EditorGUILayout.LabelField("Your current Interactive configuration", 
            "Parent: " + script.sceneParent.name + "\n",
            "Popup? " + new Func<String>(()=>{ if (script.isPopup) { return "Popup"; } else { return "Change Scene";} })()
            + "\n"
            );

玉。您还需要考虑诸如变量闭包之类的事情。所有这些都表明三元运算符是一种更干净的解决方案。

答案 1 :(得分:1)

ternary operator呢?像这样:

return script.isPopup ? "Popup" : "Change Scene";

这也可能很有帮助https://stackoverflow.com/a/38451083/2946329

答案 2 :(得分:1)

如何使用三元运算符?代替()=>{ if (script.isPopup) { return "Popup" } else { return "Change Scene"} }使用((script.isPopup) ? "Popup" : "Change Scene")
您也可以使用委托