是否可以使用运算符?并抛出新的Exception()? [英] Is it possible to use operator ?? and throw new Exception()?

查看:85
本文介绍了是否可以使用运算符?并抛出新的Exception()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

接下来我有很多方法:

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
}

我希望我可以这样使用运算符 ??

I wish I could use operator ?? like this:

return command.ExecuteScalar() as Int32? ?? throw new Exception();

但它会生成编译错误。

是否可以重写我的代码,或者只有一种方法可以做到这一点?

Is it possible to rewrite my code or there is only one way to do that?

推荐答案

对于C#7

在C#7中, throw 成为表达式,因此可以完全使用其中描述的代码问题。

In C# 7, throw becomes an expression, so it's fine to use exactly the code described in the question.

对于C#6和更早版本

在C#6和更早版本中直接 -??的第二个操作数

You can't do that directly in C# 6 and earlier - the second operand of ?? needs to be an expression, not a throw statement.

如果您实际上只是想找到一个简洁的选项,则有几种选择:

There are a few alternatives if you're really just trying to find an option which is concise:

您可以这样写:

public static T ThrowException<T>()
{
    throw new Exception(); // Could pass this in
}

然后:

return command.ExecuteScalar() as int? ?? ThrowException<int?>();

真的不建议您这样做...

I really don't recommend that you do that though... it's pretty horrible and unidiomatic.

扩展方法怎么样:

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();

还有另一种选择(同样是扩展方法):

Yet another alternative (again an extension method):

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?作为类型参数...

It's somewhat ugly because you can't specify int? as the type argument...

这篇关于是否可以使用运算符?并抛出新的Exception()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆