我应该如何在 C# 中重写一个非常大的复合 if 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/965926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I rewrite a very large compound if statement in C#?
提问by Michael Broschat
In my C# code, I have an if statement that started innocently enough:
在我的 C# 代码中,我有一个很无辜的 if 语句:
if((something == -1) && (somethingelse == -1) && (etc == -1)) {
// ...
}
It's growing. I think there must be 20 clauses in it now.
它在增长。我想现在里面肯定有20个条款。
How shouldI be handling this?
如何应该我来处理这个?
回答by J.W.
Refactor it to a function.
将其重构为一个函数。
bool Check()
{
return (something == -1) && (somethingelse == -1) && (etc == -1);
}
Alternatively, you can build more readable code/logic in your Check function.
或者,您可以在 Check 函数中构建更具可读性的代码/逻辑。
回答by chaos
Factor it out into a function and make each condition a guard clause:
将其分解为一个函数并使每个条件成为一个保护子句:
int maybe_do_something(...) {
if(something != -1)
return 0;
if(somethingelse != -1)
return 0;
if(etc != -1)
return 0;
do_something();
return 1;
}
回答by JaredPar
It looks like you have 3 pieces of information that together represent a particular state in your application. Instead of switching on these 3 pieces of state, why not create a value that encapsulates them? Then you could use an object hierarchy or a delegate at creation time to bind the action you are trying to run.
看起来您有 3 条信息,它们共同代表您的应用程序中的特定状态。与其打开这 3 个状态,为什么不创建一个封装它们的值呢?然后您可以在创建时使用对象层次结构或委托来绑定您尝试运行的操作。
回答by Mark Carpenter
You could refactor it as a function, and return an Enum value that represents the case that was true:
您可以将其重构为一个函数,并返回一个表示情况为真的 Enum 值:
if(something != -1)
return MyEnum.Something;
if(somethingelse != -1)
return MyEnum.SomethingElse;
if(etc != -1)
return MyEnum.SomethingElseEntirely;
return MyEnum.None;
回答by Martin
It's not that common to see that many clauses in one "if". You usually find that you need to nest the "ifs" to get the logic you need, when you need to execute some line regardless of the truth of some conditions. I'm not saying nest them if you don't need to, if they all need to be tested at the same time. Only if there's some common functionality. Another consideration is to set a boolean variable with the result of some set of these conditions, that might make it easier to understand. If your variables are an array or collection, could you loop through them? Are you testing them all against -1?
在一个“if”中看到许多子句并不常见。当您需要执行某些行而不管某些条件的真实性时,您通常会发现需要嵌套“ifs”以获得所需的逻辑。我不是说如果不需要的话就嵌套它们,如果它们都需要同时进行测试。仅当有一些通用功能时。另一个考虑是使用一组这些条件的结果设置一个布尔变量,这可能会使它更容易理解。如果你的变量是一个数组或集合,你能遍历它们吗?您是否正在针对 -1 测试它们?
回答by Martin
Use gates where possible.
尽可能使用门。
the if statement
if 语句
if(bailIfIEqualZero != 0 &&
!string.IsNullOrEmpty(shouldNeverBeEmpty) &&
betterNotBeNull != null &&
!betterNotBeNull.RunAwayIfTrue &&
//yadda
the refactored version
重构版本
if(bailIfIEqualZero == 0)
return;
if(string.IsNullOrEmpty(shouldNeverBeEmpty))
return;
if(betterNotBeNull == null || betterNotBeNull.RunAwayIfTrue)
return;
//yadda
回答by steamer25
Assuming all those conditions are really necessary, you could consolidate the conditions into one or more uber-booleans or function calls to enhance readability.
假设所有这些条件都是必要的,您可以将这些条件合并为一个或多个超级布尔值或函数调用以提高可读性。
E.g.,
例如,
bool TeamAIsGoForLaunch = BobSaysGo && BillSaysGo;
bool TeamBIsGoForLaunch = JillSaysGo && HymanSaysGo;
if (TeamAIsGoForLaunch && TeamBIsGoForLaunch && TeamC.isGoForLaunch())
回答by Brian
You could also factor the state into a class.
您还可以将状态分解为一个类。
class mystate
{
int something;
int somethingelse;
int etc;
bool abletodostuff()
{
return (something == -1) && (somethingelse == -1) && (etc == -1);
}
}
回答by trendels
I don't know C#, but it seems to include the conditional operator. If your conditions are short, you can replace long if/elsif/else chains with nice table-like structures, like this:
我不知道 C#,但它似乎包括条件运算符。如果您的条件很短,您可以用漂亮的类似表格的结构替换长的 if/elsif/else 链,如下所示:
return something == 0 ? 0
: somethingelse == -1 ? 1
: yetanotherthing > 2 ? 2
: 3; # default
回答by Dario
Perform aggregate operations on a list of your values.
对您的值列表执行聚合操作。
if (new[] { something, somethingelse, ... }.All(x => x == -1)) {
}
*Edit: Givin' the data an extra-line:
*编辑:给数据一个额外的行:
var Data = new[] { something, somethingelse, ... };
if (Data.All(x => x == -1)) {
}