C#中是否有类似[[noreturn]]的内容来指示编译器该方法永远不会返回值? [英] Is there something like [[noreturn]] in C# to indicate the compiler that the method will never return a value?

查看:75
本文介绍了C#中是否有类似[[noreturn]]的内容来指示编译器该方法永远不会返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的某些代码,我使用的方法看起来像这样:

For some of my code I use a method which looks like this:

public static void Throw<TException>(string message) where TException : Exception
{
    throw (TException) Activator.CreateInstance(typeof(TException), message);
}

,我想像这样使用它(简单的示例):

and I want to use it like this (simple example):

public int MyMethod()
{
    if(...)
    {
        return 42;
    }

    ThrowHelper.Throw<Exception>("Test");
    // I would have to put "return -1;" or anything like that here for the code to compile.
}

现在,很明显,我知道 MyMethod 是不可能的,因为它总是(间接)抛出异常.但是,我当然得到了编译器值并非所有路径都返回值".

now, obviously, I know that there is no way MyMethod could never return anything, because it will always (indirectly) throw an exception. But of course I get the compiler value "not all paths return a value".

这就是为什么我问我是否可以使用C ++ [[noreturn]] 属性之类的东西来向编译器指示代码实际上是有效的?

That's why I am asking if there is anything like the C++ [[noreturn]] attribute that I could use to indicate to the compiler that the code is actually valid?

为什么要使用抛出帮助器类而不是直接抛出或使用异常生成器的原因是此语句:

The reason for why I want to use a throwing helper class instead of throwing directly or using an exception builder, is this statement:

引发异常的成员不会被内联.移动构建器内部的throw语句可能允许该成员成为内联.

Members that throw exceptions are not getting inlined. Moving the throw statement inside the builder might allow the member to be inlined.

我实际上测量了代码,并且我将从内联中受益(一点点),所以我很乐于找到实现此目标的方法.

I actually measured the code and I would benefit (a little) from inlining, so I would be happy to find ways to achieve this.

推荐答案

通常的方法是抛出无分支的异常.像这样:

The normal way of doing this is to throw an exception with no branching. Something like this:

public int MyMethod()
{
    //Other code here.

    throw new InvalidOperationException();
}

我实际上想到了一种做自己想要的事情的方法:

I actually thought of a way to do what you want:

public class Thrower
{
    public static TRet Throw<TException, TRet>(string message) where TException : Exception
    {
        throw (TException)Activator.CreateInstance(typeof(TException), message);
    }

    public int MyMethod()
    {
        if (new Random().Next() == 2)
        {
            return 42;
        }

        return Throw<Exception, int>("Test");
        // I would have to put "return -1;" or anything like that here for the code to compile.
    }
}

这篇关于C#中是否有类似[[noreturn]]的内容来指示编译器该方法永远不会返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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