c# 有 shorthand "something if (condition);" 语句吗?
Does c# have a shorthand "something if (condition);" statement?
简单而简短:C# 是否有类似于 Ruby 的 shorthand if
语句?
return if (condition)
不,不是。标准方式是完全相同的长度,所以这样的 shorthand 可能是不合理的。考虑通常的语法:
if (condition) return;
对比一个假设:
return if (condition);
引入这种 'reverse' 语法的一个可能原因是 主要 意图首先被表达。因为从左到右阅读,那么它会更容易理解,从而导致更具可读性的代码。
从语言设计的角度来看,使用不同的关键字(例如 when
以防止混淆错误是有意义的。考虑以下 两 行代码:
return // missing ; here
if (condition); // no warning (except empty 'then' part)
大概应该写成:
return; // ; here present
if (condition); // unreachable code warning here
从节省字符的角度来看,它在 begin … end
语言中是有意义的。像这样的构造:
if condition begin
return;
end if;
如果写成:
会明显更短并且可能更易读
return when condition;
简单而简短:C# 是否有类似于 Ruby 的 shorthand if
语句?
return if (condition)
不,不是。标准方式是完全相同的长度,所以这样的 shorthand 可能是不合理的。考虑通常的语法:
if (condition) return;
对比一个假设:
return if (condition);
引入这种 'reverse' 语法的一个可能原因是 主要 意图首先被表达。因为从左到右阅读,那么它会更容易理解,从而导致更具可读性的代码。
从语言设计的角度来看,使用不同的关键字(例如 when
以防止混淆错误是有意义的。考虑以下 两 行代码:
return // missing ; here
if (condition); // no warning (except empty 'then' part)
大概应该写成:
return; // ; here present
if (condition); // unreachable code warning here
从节省字符的角度来看,它在 begin … end
语言中是有意义的。像这样的构造:
if condition begin
return;
end if;
如果写成:
会明显更短并且可能更易读return when condition;