【发布时间】:2010-12-18 06:42:25
【问题描述】:
接下来我有很多方法要做:
var result = command.ExecuteScalar() as Int32?;
if(result.HasValue)
{
return result.Value;
}
else
{
throw new Exception(); // just an example, in my code I throw my own exception
}
我希望我可以像这样使用运算符??:
return command.ExecuteScalar() as Int32? ?? throw new Exception();
但它会产生编译错误。
是否可以重写我的代码或者只有一种方法可以做到这一点?
【问题讨论】:
-
我希望能够
return this as T ?? that as T ?? other as T ?? throw new NotSupportedException();相反,我必须使用临时变量,测试空值,然后返回临时变量。就是丑了点。 -
在 Connect() 2016 上有一个演示文稿展示了即将推出的 C# 7 的此功能。
-
看来你在 C#7 structuredsight.com/2016/09/01/c-7-additions-throw-expressions987654321@中得到了你想要的东西
标签: c# .net nullable null-coalescing-operator