如何在 Visual Studio 中重新排序子表达式?
我想在 if 语句中重新排序子表达式。这是一个示例:
输入:
if ((a == 1) || (a == 3) || (a == 2))
{
}
所需输出:
if ((a == 1) || (a == 2) || (a == 3))
{
}
是否有任何工具可以自动对这些子表达式重新排序?
或以下相同的代码:
输入:
switch (a)
{
case: 1;
case: 3:
case: 2;
break;
}
所需输出:
switch (a)
{
case: 1;
case: 2:
case: 3;
break;
}
澄清:
我的问题未解决短路。这是一个有用的讨论,正如里德指出的那样,在大多数情况下重新排序参数是危险的。
我只是好奇 ReSharper 或 Code Rush 等解析工具是否具有此功能。这些工具可能会创建一个 AST 来执行重构,并且对它们来说重新排序子表达式不会太困难。
I would like to re-order sub expressions in an if statement. Here is an example:
Input:
if ((a == 1) || (a == 3) || (a == 2))
{
}
Desired output:
if ((a == 1) || (a == 2) || (a == 3))
{
}
Is there any tool that can automatically reorder these sub expressions?
Or the following identical code:
Input:
switch (a)
{
case: 1;
case: 3:
case: 2;
break;
}
Desired output:
switch (a)
{
case: 1;
case: 2:
case: 3;
break;
}
Clarification:
My question does not address short circuiting. This is a useful discussion, and as Reed pointed out re-ordering parameters in most cases is dangerous.
I was just curious if parsing tools such as ReSharper or Code Rush have this functionality. These tools probably create an AST to preform their refactoring and for them to reorder sub-expressions would not be too difficult.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道有什么工具可以自动执行此操作,至少在“if”语句情况下是如此。
一般来说,如果工具自动执行此操作,那就不好了。以下两个语句的行为不同:
and
在第一种情况下,如果 b != 3,但 a == 1,它将检查 a,然后检查 b,然后跳过该块。
在第二种情况下,它将检查a,然后检查c,然后检查b。你将失去短路检查的能力。
当然,在大多数情况下,这并不重要,但是当您使用方法而不是 a/b/c 的值时,它可能会很昂贵。
编辑:我发现您已更新为使用 OR 而不是 AND。 OR 也存在同样的问题,只不过短路会在第一个条件为 true 时发生,而不是在第一个条件为 false 时发生。
I don't know of a tool that would automatically do this, at least in the "if" statement case.
In general, it would be bad if a tool did this automatically. The following two statements behave differently:
and
In the first case, if b != 3, but a == 1, it will check a, then check b, then skip the block.
In the second case, it would check a, then check c, then check b. You'd lose the ability to short-circuit the checks.
Granted, in most cases, this doesn't matter, but when you're using methods instead of values for a/b/c, it can be expensive.
Edit: I see that you've updated to use OR instead of AND. The same issue exists with OR, except that the short circuit will happen when the first condition is true, instead of when the first condition is false.
我同意里德·科普西的回答。但是,由于尚未有人提及:
根据您使用的语言,
switch
语句的行为与if
/elsif/<代码>其他。我知道对于 C、Java 等,他们使用分支表来确定应该执行什么。 (不确定像 PHP 这样的东西。)维基百科文章 中提到了它,如果您想阅读更多内容。
I agree with Reed Copsey's answer. However, since no one has mentioned it yet:
Depending on the language that you use, the
switch
statement doesn't behave the same asif
/elsif
/else
. I know that for C, Java, etc. they use branch tables to determine what should be executed. (Not sure about something like PHP.) It's mentioned on the Wikipedia article, if you'd like to read more.