將引發錯誤,因爲你的功能的情況下不返回任何東西你沒有進入你的foreach
聲明。當你的函數返回一個long
的值時,你需要返回任何情況下函數結尾的值。我認爲問題在於你錯位了你的第二個回報,它應該在foreach
循環之外。
private long GetStakeholderId()
{
string currentUserId = _userManager.GetUserId(User);
long stakeholderId;
var users = _userManager.Users;
foreach (var user in users)
{
if (user.Email == currentUserId)
{
var idForStakeholder = user.Id;
var stakeholders = _context.Stakeholders;
foreach (var stakeholder in stakeholders)
{
if (stakeholder.IdentityId == idForStakeholder)
{
stakeholderId=stakeholder.StakeholderId;
return stakeholderId;
}
else
{
return 0;
}
}
}
}
return 0; // 0 will be returned in any case if you reach the end of the function
}
你可能不得不小心你當前的邏輯。如果你的用戶的第一個利益相關者不是好的,你直接返回0,而不是檢查其他的。只有當您的利益相關者ID都不對應您正在查找的人時,纔可能要放置您的return 0
。把它放在那裏是很好的,因爲你不需要檢查其他用戶,並且可以直接退出該功能。
private long GetStakeholderId()
{
string currentUserId = _userManager.GetUserId(User);
long stakeholderId;
var users = _userManager.Users;
foreach (var user in users)
{
if (user.Email == currentUserId)
{
var idForStakeholder = user.Id;
var stakeholders = _context.Stakeholders;
foreach (var stakeholder in stakeholders)
{
if (stakeholder.IdentityId == idForStakeholder)
{
stakeholderId=stakeholder.StakeholderId;
return stakeholderId;
}
}
return 0; // If none of the stakeholder ID correspond to the one you are looking for, it means it doesn't exist. You can return 0 directly there.
}
}
return 0; // This part of code will be reached if the user is not found.
}
如果它沒有進入for循環,那麼它將如何返回。您需要在for循環之外返回 – Nkosi
當沒有用戶時它不返回 – Mafii
寫返回0;外部foreach循環 –