有没有一个标准"永远不会返回"属性为C#的功能呢? [英] Is there a standard "never returns" attribute for C# functions?

查看:175
本文介绍了有没有一个标准"永远不会返回"属性为C#的功能呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法是这样的:

I have one method that looks like this:

void throwException(string msg)
{
    throw new MyException(msg);
}

现在如果我写

int foo(int x, y)
{
    if (y == 0)
        throwException("Doh!");
    else
        return x/y;
}

编译器会抱怨富说:不是所有的路径返回一个值。

the compiler will complain about foo that "not all paths return a value".

有没有我可以添加到throwException以避免属性?是这样的:

Is there an attribute I can add to throwException to avoid that ? Something like:

[NeverReturns]
void throwException(string msg)
{
    throw new MyException(msg);
}

我怕自定义属性不会做,因为我的目的我需要编译器的合作。

I'm afraid custom attributes won't do, because for my purpose I'd need the cooperation of the compiler.

推荐答案

没有。我建议你​​改变你的第一个函数的签名,返回例外,而不是扔掉它,并留下throw语句在你的第二个功能。这将会使编译器高兴,闻起来不那么糟糕,以及。

No. I suggest you change the signature of your first function to return the exception rather than throw it, and leave the throw statement in your second function. That'll keep the compiler happy, and smells less bad as well.

这篇关于有没有一个标准"永远不会返回"属性为C#的功能呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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