c# - 可以使用运算符吗??并抛出新的异常()?

标签 c# .net nullable null-coalescing-operator

接下来我有很多方法要做:

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/

相关文章:

c# - 为反向字符串组合实现 Levenshtein 距离?

c# - 从调用方法中获取参数名称

c# - .NET ref 参数是线程安全的,还是容易受到不安全的多线程访问的影响?

objective-c - Objective-C 中可为空、__nullable 和 _Nullable 之间的区别

c# - 具有 C# 8 可空引用类型的 TryGetValue 模式

c# - GDI+画线算法

c# - 保存父级时,嵌套的现有实体会重复

c# - Windows RT 应用程序中的图像闪烁

c# - 为什么 C# 中的字节减法需要强制转换?

string - 在 kotlin 中,空对象的 toString() 方法返回空字符串而不是 "null"的最佳方法是什么