我有一個集中的方法來檢查存盤庫中的結果。這包括檢查Entity屬性是否為空。
可悲的是,這具有顯示編譯器警告的煩人副作用,因為在包含呼叫的方法中沒有空檢查。
這可能是一個很長的鏡頭,但是有沒有辦法告訴編譯器將我的方法視為手動空檢查?我不希望全域禁用警告,因為它實際上非常有用。還有其他解決方法嗎?
public Group GetGroup(Group.GroupId groupId)
{
if (groupId.Value == null || groupId.Is(0))
throw new Exception("Can not get group with ID: null/0");
EntityInteractionResult<Group> readResult = _groupRepository.ReadById((ulong)groupId.Value);
readResult.ValidateSuccessAndEntity(); // <- This checks if Entity is null
return readResult.Entity; // <- CS8603 possible null reference return
}
uj5u.com熱心網友回復:
If ValidateSuccessAndEntityis method of EntityInteractionResultthen 你可以MemberNotNullAttribute用來列出當方法回傳時不會為空的成員:
public class Result
{
public string? Value { get; set; }
public Result()
{
}
[MemberNotNull(nameof(Value))]
public void Validate()
{
if(Value is null)
throw new Exception();
}
}
var result = new Result();
result.Validate();
var c = result.Value[1]; // "warning CS8602: Dereference of a possibly null reference" if previous line commented out
演示
閱讀更多:
- C# 編譯器解釋的空狀態靜態分析的屬性
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/523974.html
上一篇:如果選擇回傳0則執行另一個選擇
