透過模擬登入驗證情境,示範 C# 常見運算子的實務應用:
==, !=, <, >)&&, ||, !)?:)??)is, switch)// 模擬資料庫查詢結果
string dbUsername = "admin";
string dbPasswordHash = "A665A45920422F9D417E4867EFDC4FB8A04A1F3FFF1FA07E998E86F7F7A27AE3"; // SHA256("123456")
bool dbIsActive = true;
int dbFailedAttempts = 0;
DateTime? dbLastLogin = DateTime.Now.AddDays(-5);
public class AuthResult
{
public bool Success { get; set; }
public string Message { get; set; }
public bool Requires2FA { get; set; }
}
public AuthResult ValidateLogin(string inputUser, string inputPass)
{
var result = new AuthResult();
// 1. 空值檢查 (空值合併運算子 ??)
string user = inputUser?.Trim() ?? string.Empty;
string pass = inputPass ?? string.Empty;
// 2. 基本格式驗證 (關係/邏輯運算子)
if (user.Length == 0 || pass.Length == 0)
{
result.Message = "帳號密碼不可為空";
return result;
}
if (user.Length > 20 || pass.Length > 100)
{
result.Message = "輸入長度超過限制";
return result;
}
// 3. 帳號比對 (字串比較,序數比較區分大小寫)
bool userMatch = string.Equals(user, dbUsername, StringComparison.Ordinal);
// 4. 密碼驗證 (這裡簡化為直接比對雜湊,實務應用 BCrypt/Argon2)
string inputHash = ComputeSha256(pass);
bool passMatch = string.Equals(inputHash, dbPasswordHash, StringComparison.OrdinalIgnoreCase);
// 5. 綜合邏輯判斷 (短路求值 && ||)
if (!userMatch || !passMatch)
{
// 失敗計數 (模擬)
dbFailedAttempts++;
result.Message = "帳號或密碼錯誤";
// 條件運算子 ?:
result.Message += dbFailedAttempts >= 5 ? ",帳號已鎖定,請聯繫管理員" : "";
return result;
}
// 6. 帳號狀態檢查
if (!dbIsActive)
{
result.Message = "帳號已停用";
return result;
}
// 7. 登入成功
result.Success = true;
result.Message = "登入成功";
// 8. 進階判斷:是否需雙因子認證 (模式比對 switch expression C# 8)
result.Requires2FA = dbLastLogin switch
{
null => true, // 首次登入
DateTime d when (DateTime.Now - d).TotalDays > 30 => true, // 超過 30 天未登入
_ => false
};
// 重置失敗計數
dbFailedAttempts = 0;
dbLastLogin = DateTime.Now;
return result;
}
// 簡易 SHA256 (示範用,實務用 BCrypt)
string ComputeSha256(string input)
{
using (var sha = System.Security.Cryptography.SHA256.Create())
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input);
byte[] hash = sha.ComputeHash(bytes);
return BitConverter.ToString(hash).Replace("-", "").ToUpperInvariant();
}
}
| 分類 | 運算子 | 範例 | 說明 |
|---|---|---|---|
| 關係 | == | a == b | 值相等 (參考型別比較參考,值型別比較值) |
!= | a != b | 值不相等 | |
< > <= >= | age >= 18 | 大小比較 | |
is | obj is string | 型別測試 (C# 7+ 支援模式) | |
| 邏輯 | && | a && b | 邏輯 AND,短路 (a false 則不評估 b) |
|| | a || b | 邏輯 OR,短路 (a true 則不評估 b) | |
! | !flag | 邏輯 NOT | |
| 條件 | ?: | x > 0 ? "正" : "負" | 三元運算子,唯一三元運算子 |
| 空值合併 | ?? | name ?? "Guest" | 左運算元非 null 取左,否則取右 |
| 空值條件 | ?. | user?.Name | 物件為 null 回傳 null,不拋例外 |
u switch
{
null => "不存在",
{ IsActive: false } => "停用",
{ FailedAttempts: >= 5 } => "鎖定",
{ LastLogin: null } => "未啟用",
{ LastLogin: var dt } when (DateTime.Now - dt).TotalDays > 90 => "長期未登入",
_ => "正常"
};
StringComparison.Ordinal 避免文化特性導致的比較差異 (如土耳其語 I/ı 問題)。