已做null检查仍触发CS8602警告,如何消除该空引用提示?
问题原因
C#的空引用分析器无法追踪void方法内部对字段的赋值操作。你调用LoadConversationService()后,编译器没办法确认这个方法一定会把conversationService设为非null,所以依然认为后续的调用存在空引用风险。
解决方法
有两种简洁的方案可以消除警告,不用!语法:
方案1:修改LoadConversationService为返回实例的方法
把方法改成返回新创建的实例,直接在检查null时赋值,让编译器能明确看到字段被赋值为非null:
public string GetNextState(string input) { if (conversationService == null) conversationService = LoadConversationService(); List<ConversationResponse> responses = conversationService.PredictResponse(new Conversation(input)); return responses.First().Text; } private ConversationService LoadConversationService() { return new ConversationService(); }
或者用更简洁的空合并运算符写法:
conversationService = conversationService ?? LoadConversationService();
方案2:使用MemberNotNull属性标注方法
如果不想修改方法返回值,可以给LoadConversationService添加[MemberNotNull]属性(需要.NET 5及以上版本,或在项目中引入Nullable NuGet包),告诉编译器这个方法执行后conversationService一定非null:
using System.Diagnostics.CodeAnalysis; // ... [MemberNotNull(nameof(conversationService))] public void LoadConversationService() { conversationService = new ConversationService(); }
添加这个属性后,编译器会识别出调用该方法后conversationService不再为null,警告自然消失。
内容的提问来源于stack exchange,提问作者Totte
相关产品推荐
相关产品推荐

