What's wrong with this boolean iteration?
While doing this bool iteration, I was tempted to use the non existing operator ||=
, and figured there must be a simpler or better design that would replace its valid use (rather than think it's just "missing"):
bool validExtension = false;
foreach (string extension in Plugin.Extensions)
{
validExtension = validExtension || Path.GetExtension(file).Equals(extension.TrimStart('*'), StringComparison.InvariantCultureIgnoreCase);
if (validExtension)
{
break;
}
}
importButton.Enabled = File.Exists(importTextBox.Text) 开发者_StackOverflow社区&& validExtension;
That loop has an invariant: on entry to the body, validExtension = false
.
So the body can be simplified to:
if (validExtension = Path.GetExtension(file).Equals(extension.TrimStart('*'), StringComparison.InvariantCultureIgnoreCase))
break;
If there wasn't such an invariant, you could use the compound assignment operator |=
if you always wanted to evaluate the right-hand side, or if (!lhs) lhs = rhs;
if you wanted short-circuiting.
foreach (string extension in Plugin.Extensions)
{
if (Path.GetExtension(file).Equals(extension.TrimStart('*'), StringComparison.InvariantCultureIgnoreCase))
{
validExtension = true;
break;
}
}
This works because you are breaking the first time you find a valid extension, so validExtension
is always false on the first line of the loop.
can't you just say validExtension = Path.Get....
since at the start of the expression validExtension will always be false.
While there is no ||=
operator in C#, there is the |=
operator that may be what you're looking for.
MSDN Reference
If its a string[], the whole code can be changed like this
Func<string[], string, bool> validExtension = (arr, s) => arr.Contains(s);
importButton.Enabled = validExtension(Plugin.Extensions, Path.GetExtension(file)) && File.Exists(importTextBox.Text);
For checking a value inside an Array you could always use Array.Contains
extension method.
P.S: I have reversed the tests as Ben Voigt rightfully said
精彩评论