Predicate in a method signature, Lambda expression
The code below is just an exa开发者_运维问答mple. The predicate of string is a I'm wondering if the code below may not be written more simply :
public static bool IsValid(Predicate<string> condition, string test)
{
return condition(test);
}
And the call :
Validator.IsValid(s => s.StartsWith("Test"), "Test with a lambda expression")
EDIT
Sorry for the lack of details. The code above is just an example but the IsValid method will take a Predicate parameter, not a Predicate so here the signature :
public static bool IsValid(Predicate<T> condition, T obj)
{
return condition(obj);
}
Personally I think it's cleaner to put the lambda as the last parameter, wherever possible, as it's makes the code easier to read:
public static bool IsValid(T obj, Predicate<T> condition)
{
return condition(obj);
}
Validator.IsValue(foo,f=>f.Value==1);
Yes, it can be written more simply:
"Test with a lambda expression".StartsWith("Test")
Your IsValid
method adds absolutely no value here... If you know the predicate you're going to pass to IsValid
, why can't you evaluate it directly instead of calling a "helper" method?
精彩评论