c# - C# 中是否有 "true or throw"或 "non-null or throw"表达式?

标签 c# expression throw

鉴于此工作代码:

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/

相关文章:

javascript - JS函数再次调用时不会创建另一个二维码对象

c# - 限制 ReportViewer 控件中下拉列表的选项

mysql - 基于其他列sql更新列的表达式

正则表达式中的 C++ 特殊字符

java - MapStruct @Mapping(表达式 ="java(...)")

c++ - 如何实现throw语句做一个整数值

java - 通过java Throwable抛出嵌套异常

c# - 如何对操作施加时间限制约束

c# - 如何在不暂停或中断程序的情况下在 C# 中多线程读取行?

Java异常处理