Jas*_*n O 0 c# lambda collection-initializer
我正在设计一个状态机类,并希望使用lambda表达式来表示满足状态转换对象的条件.当我创建一个新的状态转换对象时,我还想传递一个条件列表,它可以用来评估是否转移到下一个状态.但是,我在初始化条件列表时遇到了问题.这是一个示例,简化的代码示例,说明了我遇到的问题:
// Alias for delegate function
using Condition = Func<int, bool>;
class SomeStateClass
{
public void SomeFuncToCreateConditionList()
{
List<Condition> conditions = new List<Condition>({
{ new Condition(x => x > 5) },
{ new Condition(x => x > 5 * x) }
});
}
}
Run Code Online (Sandbox Code Playgroud)
我得到一个语法错误就行了柯利括号List<Condition>({说法) expected,并在右括号的另一种语法错误说
new Condition(
; expected
} expected
Run Code Online (Sandbox Code Playgroud)
我确信这里有一些愚蠢的东西,但我一直盯着它看似太久了,似乎无法发现它.任何想法?
您的List-initializer中有错误.
它应该是new List<Condition> { ... }代替new List<Condition>({...})
你也不需要将每个包裹new Condition()在大括号中.
这应该工作:
// Alias for delegate function
using Condition = Func<int, bool>;
class SomeStateClass
{
public void SomeFuncToCreateConditionList()
{
List<Condition> conditions = new List<Condition>
{
new Condition(x => x > 5),
new Condition(x => x > 5 * x)
};
}
}
Run Code Online (Sandbox Code Playgroud)
或者,更短的方法:
public void SomeFuncToCreateConditionList()
{
var conditions = new List<Condition>
{
x => x > 5,
x => x > 5 * x
};
}
Run Code Online (Sandbox Code Playgroud)