空检查失败 C#

Null checker fails C#

我的空检查器失败了,这是怎么回事?

我正在尝试检查用户声明是否确实存在变量 sID,它只是回发模型的 staffID

所以我添加了一个 try catch 语句来阻止它崩溃

  var sID = ViewModel_CreateNewAgent.Tbl_Brands_Staff.BranchStaffID.ToString();
  var staffIDExists = _context.AspNetUserClaims.Where(c => c.ClaimValue == sID).FirstOrDefaultAsync();

                    /// VALIDATE STAFF ID
                    var claimsExists = await _userManager.GetClaimsAsync(user);
                
                    var doesStaffIDExist ="";
                    try
                    {
                        doesStaffIDExist = staffIDExists.Result.ClaimValue ?? doesStaffIDExist;
                        //doesStaffIDExist = staffIDExists.Result.ClaimValue != null ? staffIDExists.Result.ClaimValue : doesStaffIDExist ;
                    }catch(Exception err) { }

不要将 try-catch 用于正常工作流程,尝试解决真正的问题。

此处staffIDExistsand/orstaffIDExists.Resultand/orClaimValue可能是null。使用 null conditional operator ? 使您的代码安全且可读:

var staffIDExists = _context.AspNetUserClaims.Where(c => c.ClaimValue == sID).FirstOrDefaultAsync();
string doesStaffIDExist = claimsExists?.Result?.ClaimValue ?? "";

但是,该代码有意义吗? Where 检查 c.ClaimValue == sID,因此 doesStaffIDExist 总是 ""(如果没有这样的声明)或 sid.

I am trying to check if the user claims does exist for the variable sID

嗯,那么这段代码会更简单:

return _context.AspNetUserClaims.Any(c => c.ClaimValue == sID);