我看到了很多有关此错误的问题,但所有/大多数都包含复杂的代码或类型。
我使用这一行很多年了,提示方法名称时出错:
string currentMethod = System.Reflection.MethodBase.GetCurrentMethod().Name;
Run Code Online (Sandbox Code Playgroud)
但现在我得到这个错误:
警告 CS8602:取消引用可能为空的引用。
我应该更改什么/是否有另一种方法可以获取当前方法的名称而不出现此错误?
谢谢
Fri*_*ied 16
GetCurrentMethod() 被声明为能够返回空值。如果您确定该值不为空,则可以使用允许空值的“!” 运算符例如
string currentMethod = System.Reflection.MethodBase.GetCurrentMethod()!.Name;
Run Code Online (Sandbox Code Playgroud)
请参阅https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving
虽然您可能确实有未处理的空变量或属性,但可以看出 CS8602 很容易出现误报。 https://github.com/dotnet/roslyn/issues/44805 和https://github.com/dotnet/roslyn/issues/49653
这些是人们费心报告的几个复杂场景,但根据我的经验,即使是更简单的场景(具有非常明确的先前空检查)仍然可能导致此警告。
由于消除此警告的努力可能会导致您将不可为空的字段设置为空,只是为了使警告消失,因此 CS8602 的解决方案通常比问题本身更糟糕。
答案:降低警告级别,直到修复误报。
小智 -2
问题很清楚。该名称在某些时候可能为空。尝试使用?因此编译器会知道您知道来自 System.Reflection.MethodBase.GetCurrentMethod().Name 的可能为 null;
用法:
string? currentMethod = System.Reflection.MethodBase.GetCurrentMethod().Name;
Run Code Online (Sandbox Code Playgroud)
文档:在此处阅读更多信息。