我有一个抛出异常的方法:
public void MyMethod()
{
// do some logging
throw new Exception("My Text");
}
我在我的代码中的 100 多个地方使用了这个方法,问题是当我在另一个必须返回值的方法中使用这个方法时,Re-sharper 不理解不需要返回值,例如:
public int AnotherMethod()
{
// some stuff
MyMethod(); // <= it always throws exception
return 0; // i have to put this code, while it never executes
}
有没有办法告诉 Re-sharper MyMethod 是一个异常,就像这样:
public int AnotherMethod()
{
// some stuff
throw new Exception(); // <= it always throws exception
//return 0; <= this line is no more needed
}
最佳答案
这里有两个问题。
首先,您可以向 ReSharper 提示代码分析,我将在下面向您展示如何操作。
然而,这里的问题不是 ReSharper,而是编译器。编译器不会被这些提示说服。你展示的方法:
public int AnotherMethod()
{
// some stuff
MyMethod(); // <= it always throws exception
return 0; // i have to put this code, while it never executes
}
即使您说服 ReSharper 理解 MyMethod
总是抛出异常,也必须这样写。这与 ReSharper 无关,这只是 C# 编译器。
为了告诉 ReSharper 您的方法以某种方式运行,您可以使用属性对其进行标记。您需要将这些属性的源代码副本复制到您的项目中,或者引用 ReSharper 注释程序集。完成后,您可以像这样标记 MyMethod
:
[ContractAnnotation("=> halt")]
public void MyMethod()
...
但是,C# 编译器不会关心这个,仍然会提示缺少返回值。
您可以阅读更多有关 ReSharper 理解的各种属性的信息 here: ReSharper Code Annotations Attributes .
关于c# - 我怎么能让 Resharper 或 Intellisense 知道一个方法总是抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764350/