我怀疑您正在寻找在 C# 7 中添加的throw 表达式。
return mode == BuildMode.Debug ? true
: mode == BuildMode.MemoryProfiling ? true
: mode == BuildMode.Release ? false
: throw new Exception(...);
最常见的用法之一是空参数验证
var nameValue = value ?? throw new ArgumentNullException(paramName: nameof(value), message: "New name must not be null");
懒惰的评价
对于惰性评估,您必须返回一个函数或一个 Lazy :
Lazy<bool> IsDebugMode(BuildMode mode)
{
bool isDebug()
{
return mode == BuildMode.Debug ? true
: mode == BuildMode.MemoryProfiling ? true
: mode == BuildMode.Release ? false
: throw new Exception(...);
}
return new Lazy<bool>(isDebug);
}
并将其用作:
var isDbg=IsDebugMode(someMode);
.....
.....
//Will throw here!
if (isDbg.Value)
{
...
}
F# 提供惰性计算,它还返回一个具有更方便语法的惰性计算:
let isDebugMode mode =
match mode with
| BuildMode.Debug -> true
| BuildMode.Release -> false
| _ -> failwith "Ouch!"
let isDbg = lazy (isDebugMode someMode)
...
//Can throw here
if (isDbg.Force() then
...
使用 Func 进行相同的惰性求值:
Func<bool> IsDebugMode(BuildMode mode)
{
bool isDebug()
{
return mode == BuildMode.Debug ? true
: mode == BuildMode.MemoryProfiling ? true
: mode == BuildMode.Release ? false
: throw new Exception(...);
}
return isDebug;
}
用作函数:
var isDbg=IsDebugMode(someMode);
...
//Can throw here
if(isDbg())
{
...
}
开关表达式
C# 8 将添加可能如下所示的开关表达式:
return mode switch {
BuildMode.Debug => true,
BuildMode.MemoryProfiling => true,
BuildMode.Release => false,
_ => throw new Exception (...)
};
惰性函数可能如下所示:
Lazy<bool> IsDebugMode(BuildMode mode)
{
bool isDebug() =>
mode switch {
BuildMode.Debug => true,
BuildMode.MemoryProfiling => true,
BuildMode.Release => false,
_ => throw new Exception (...)
};
return new Lazy<bool>(isDebug);
}
看起来有点像 F#