接下来我有很多方法要做:
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();
但它会产生编译错误。
是否可以重写我的代码,或者只有一种方法可以做到这一点?
最佳答案
对于 C# 7
在 C# 7 中,throw
成为一个表达式,因此可以完全使用问题中描述的代码。
对于 C# 6 及更早版本
您不能在 C# 6 和更早版本中直接这样做 - ?? 的第二个操作数需要是表达式,而不是 throw 语句。
如果您真的只是想找到一个简洁的选项,那么有几种选择:
你可以这样写:
public static T ThrowException<T>()
{
throw new Exception(); // Could pass this in
}
然后:
return command.ExecuteScalar() as int? ?? ThrowException<int?>();
不过,我真的不建议您这样做...这非常可怕且不合常理。
扩展方法怎么样:
public static T ThrowIfNull(this T value)
{
if (value == null)
{
throw new Exception(); // Use a better exception of course
}
return value;
}
然后:
return (command.ExecuteScalar() as int?).ThrowIfNull();
还有另一种选择(也是一种扩展方法):
public static T? CastOrThrow<T>(this object x)
where T : struct
{
T? ret = x as T?;
if (ret == null)
{
throw new Exception(); // Again, get a better exception
}
return ret;
}
调用:
return command.ExecuteScalar().CastOrThrow<int>();
这有点难看,因为你不能将 int?
指定为类型参数...
关于c# - 可以使用运算符吗??并抛出新的异常()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1762772/