在C#中是否有类似]的东西来表示编译器该方法永远不会返回值?

对于我的一些代码,我使用了一个如下所示的方法:

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

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

 public int MyMethod() { if(...) { return 42; } ThrowHelper.Throw("Test"); // I would have to put "return -1;" or anything like that here for the code to compile. } 

现在,显然,我知道MyMethod永远无法返回任何东西,因为它总是(间接地)抛出exception。 但是我当然得到编译器值“并非所有路径都返回一个值”。

这就是为什么我问是否有类似C ++ [[noreturn]]属性的东西,我可以用来向编译器表明代码实际上是有效的


编辑:我想要使​​用抛出辅助类而不是直接抛出或使用exception构建器的原因是这个声明 :

抛出exception的成员不会被内联。 在构建器中移动throw语句可能允许成员内联。

我实际测量了代码,我会从内联中获益(一点点),所以我很乐意找到实现这一目标的方法。

执行此操作的常规方法是抛出没有分支的exception。 像这样的东西:

 public int MyMethod() { //Other code here. throw new InvalidOperationException(); } 

我实际上想到了一种方法来做你想要的:

 public class Thrower { public static TRet Throw(string message) where TException : Exception { throw (TException)Activator.CreateInstance(typeof(TException), message); } public int MyMethod() { if (new Random().Next() == 2) { return 42; } return Throw("Test"); // I would have to put "return -1;" or anything like that here for the code to compile. } } 

不,没有办法让编译器理解该方法将始终抛出exception,从而标志着代码执行的结束。

你被迫

  1. 将方法作为方法的最后一个语句调用(如果方法void
  2. 或者在方法调用之后添加必要的流控制语句以结束执行, 即使代码永远不会实际执行

正如您所指出的,在具有返回类型的方法中,您将被强制写入适当的return X; 声明其中X是方法的返回类型的适当值。

没有办法解决这个问题。