鉴于此工作代码:
if (!this.TryParse()) throw new Exception();
// or
if (this.Parse() == null) throw new Exception();
因为 C# 7 知道使用 ??
来抛出表达式和 ?:
已经,我想知道是否(或为什么不)有一种方法可以在 C# 中将其编写为“true or throw”或“non-null or throw”语句,类似于 JavaScript 或 PHP 等其他语言所允许的。这是我尝试过的:
// COMPILE ERROR:
this.TryParse() || throw new Exception();
this.Parse() ?? throw new Exception();
_ = this.TryParse() || throw new Exception();
// WORKS:
_ = this.TryParse() ? 0 : throw new Exception();
_ = this.Parse() ?? throw new Exception();
特别是,为什么 _ = <obj> ?? <throw>
工作但_ = <bool> || <throw>
不是吗?
我为什么要这样做?纯粹的可读性:我想让主要目的是做而不是测试的方法作为调用语句在行的开头清晰可见,而不是将它们隐藏在 if 条件中。以 PHP 为例:
mysql_connect(...)
OR die();
最佳答案
这种情况下可以使用扩展方法...
static void Main(string[] args)
{
var a = false;
a.OrThrow();
}
}
public static class ThrowExtension {
public static void OrThrow(this bool b)
{
if(!b)
throw new Exception();
}
}
关于c# - C# 中是否有 "true or throw"或 "non-null or throw"表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56613707/