Mar*_*don 18 .net c# asp.net-web-api
你能解释一下这段奇怪的代码吗?
expression.Compile()();
Run Code Online (Sandbox Code Playgroud)
为什么这里有两对括号?我没有在谷歌找到任何东西.完整的方法是
public Validator NotEmpty(Expression<Func<IEnumerable<T>>> expression)
{
var member = (MemberExpression)expression.Body;
string propertyName = member.Member.Name;
IEnumerable<T> value = expression.Compile()();
if (value == null || !value.Any())
{
ValidationResult.AddError(propertyName, "Shouldn't be empty");
}
return this;
}
Run Code Online (Sandbox Code Playgroud)
它是这样使用的:
_validator.NotEmpty(() => request.PersonIds); // request.PersonIds is List<int>
Run Code Online (Sandbox Code Playgroud)
此方法检查集合是空还是空.一切正常,但我对该代码有点困惑.我以前从未见过在C#中使用过两对括号.这是什么意思?
Rom*_*syk 25
好吧,您将int列表作为表达式树传递给方法.该表达式产生IEnumerable<T>(在这种情况下IEnumerable<int>)的值.
要获取表达式的值,您需要将此表达式编译为委托Func<IEnumerable<T>>,然后调用委托.实际上,我可以编写两行独立的代码而不是上面使用的较短语法:
Func<IEnumerable<T>> del = expression.Compile();
IEnumerable<T> value = del();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2101 次 |
| 最近记录: |