清晰与否:C#多个三元运营商+扔如果无法比拟的 [英] Legible or not: C# multiple ternary operators + Throw if unmatched
问题描述
你觉得下面的C#代码清晰?
Do you find the following C# code legible?
private bool CanExecuteAdd(string parameter) {
return
this.Script == null ? false
: parameter == "Step" ? true
: parameter == "Element" ? this.ElementSelectedInLibrary != null && this.SelectedStep != null
: parameter == "Choice" ? this.SelectedElement != null
: parameter == "Jump" ? this.SelectedStep != null
: parameter == "Conditional jump" ? false
: false.Throw("Unknown Add parameter {0} in XAML.".F(parameter));
}
在那里投掷定义为:
where Throw is defined as:
public static T Throw<T>(this T ignored, string message) {
throw new Exception(message);
}
我知道这不是地道的C#。但是,您将能够在在第一或第二看就懂了吗?还是我太远?
I know that's not idiomatic C#. However, would you be able at understand it at first or second glance? Or did I stray too far?
推荐答案
我已经使用这种代码Java中的相当数量。我不喜欢 false.Throw
位,但有多重条件语句像这样(尤其是格式化这样)我认为是好的。
I've used this sort of code in Java a fair amount. I don't like the false.Throw
bit, but having multiple conditionals like this (particularly formatted this way) is fine in my view.
这是你第一次看到它稍显陌生,但在那之后,它只是一个方便的模式了解。
It's slightly strange the very first time you see it, but after that it's just a handy pattern to know about.
一个替代使用 false.Throw
这里会是这样的:
One alternative to using false.Throw
here would be something like this:
bool? ret = this.Script == null ? false
: parameter == "Step" ? true
: parameter == "Element" ? this.ElementSelectedInLibrary != null && this.SelectedStep != null
: parameter == "Choice" ? this.SelectedElement != null
: parameter == "Jump" ? this.SelectedStep != null
: parameter == "Conditional jump" ? false
: null;
if (ret == null)
{
throw new ArgumentException(
string.Format("Unknown Add parameter {0} in XAML.", parameter);
}
return ret.Value;
编辑:其实,在这情况下,我不会用任何的if / else的或的这种模式...我会使用开关/箱这可能是,如果你想非常紧凑:
Actually, in this case I wouldn't use either if/else or this pattern... I'd use switch/case. This can be very compact if you want:
if (this.Script == null)
{
return false;
}
switch (parameter)
{
case "Step": return true;
case "Element": return this.ElementSelectedInLibrary != null && this.SelectedStep != null;
case "Choice": return this.SelectedElement != null;
case "Jump": return this.SelectedStep != null;
default: throw new ArgumentException(
string.Format("Unknown Add parameter {0} in XAML.", parameter);
}
这篇关于清晰与否:C#多个三元运营商+扔如果无法比拟的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!