C#.NET 3.5。我试图理解C#Action对象的内在限制。在lamda中(实际上是lamdas?),我们可以执行赋值,调用函数,甚至执行三元操作,但是我们不能执行多语句操作。C#操作的限制lambda代码块
这是因为单语句执行只是语法糖包装它在委托?为什么下面的第一个例子不起作用?
public class MyClass
{
private int m_Count = 0;
public void Test()
{
int value = 0;
// Does not work, throws compile error
Action action =() => { if(m_Count < 10) m_Count++; value = m_Count; }
// Works
Action action2 =() => value = delegate(){
if(m_Count < 10)
m_Count++;
return m_Count;
};
// Works
Action action3 =() => value = m_Count;
// Works
Action action4 =() => value = m_Count < 10 ? m_Count++ : 0;
// Works
Action action5 =() => value = Increment();
}
public int Increment()
{
if (m_Count < 10)
m_Count++;
return m_Count;
}
}
编辑:Grr,抱歉的噪音。我本来
Action action =() => if(m_Count < 10) m_Count++; value = m_Count;
扔哪一个编译错误,但我想我会尝试在括号
Action action =() => { if(m_Count < 10) m_Count++; value = m_Count; }
其中还扔了一个编译错误,它包裹后前右,所以我跳下得出的结论是这是同样的问题。如果我在大括号后面用分号折腾
Action action =() => { if(m_Count < 10) m_Count++; value = m_Count; };
不好意思!
编辑2:感谢cfeduke,你发布,在我上面编辑的同时 - 继续并标记为答案。
不能立即看到有什么问题 - 你得到了什么编译错误? – 2008-10-24 16:27:49