C# 中鮮為人知的強大運算符
C# 還提供了一些"冷門"但功能強大的運算符,這些運算符在特定場景下能極大簡化代碼并提高效率。
1. 空合并賦值運算符 ??=
// 傳統寫法
if (variable == null)
{variable = defaultValue;
}// 使用 ??=
variable ??= defaultValue;
功能:
當變量為 null
時,將右側的值賦給它
實際應用:
// 延遲初始化
private List<Item> _items;
public List<Item> Items => _items ??= new List<Item>();// 配置默認值
void LoadSettings()
{_qualityLevel ??= QualityLevel.High;_resolution ??= new Resolution(1920, 1080);
}
2. 空條件運算符 ?.
和 ?[]
// 安全訪問成員
string name = user?.Profile?.Name;// 安全訪問索引器
int? firstScore = scores?[0];// 安全調用方法
user?.Validate();
功能:
在訪問成員、調用方法或訪問索引器時,如果對象為 null
,則返回 null
而不是拋出異常
實際應用:
// Unity 中安全訪問組件
Rigidbody rb = go?.GetComponent<Rigidbody>();// 安全訪問字典值
var config = settings?.GetSection("Graphics")?["Resolution"];
3. 范圍運算符 ..
int[] numbers = { 0, 1, 2, 3, 4, 5 };
var slice = numbers[1..4]; // [1, 2, 3]
var allButFirst = numbers[1..]; // [1, 2, 3, 4, 5]
var lastThree = numbers[^3..]; // [3, 4, 5]
功能:
創建數組或集合的切片視圖
實際應用:
// 處理部分數據
ProcessFrames(videoFrames[10..20]);// 獲取子字符串
string domain = email[(email.IndexOf('@') + 1)..];
4. 索引運算符 ^
int[] numbers = { 0, 1, 2, 3, 4, 5 };
int last = numbers; // 5
int secondLast = numbers; // 4
功能:
從集合末尾開始索引
實際應用:
// 獲取路徑最后部分
string fileName = path.Split('/');// 檢查最后幾個元素
if (samples[^3..].All(s => s > threshold))
{// 最后三個樣本都超過閾值
}
5. 模式匹配中的 is
和 switch
表達式
// is 模式匹配
if (obj is string { Length: > 5 } s)
{Console.WriteLine($"長字符串: {s}");
}// switch 表達式
var message = input switch
{int i when i > 0 => "正數",int i when i < 0 => "負數",int => "零",_ => "非數字"
};
功能:
強大的類型檢查和值提取
實際應用:
// Unity 組件處理
void ProcessComponent(Component comp)
{switch (comp){case Rigidbody rb:rb.velocity = Vector3.zero;break;case Renderer rend when rend.material != null:rend.material.color = Color.red;break;case null:Debug.LogWarning("組件丟失");break;}
}
6. 棄元運算符 _
// 忽略不需要的輸出參數
_ = int.TryParse("123", out _);// 忽略不需要的返回值
_ = Task.Run(() => BackgroundProcess());// 模式匹配中忽略部分值
if (point is (0, _))
{// X坐標為0的所有點
}
功能:
明確表示忽略某個值
實際應用:
// Unity 事件處理
button.onClick.AddListener(_ =>
{// 不需要事件參數PlaySound();
});// 解構忽略部分值
var (x, _, z) = GetPosition();
7. 命名參數和可選參數
void ConfigureServer(string host, int port = 8080, bool ssl = false)
{// ...
}// 調用時
ConfigureServer("example.com", ssl: true);
功能:
提高代碼可讀性并簡化重載
實際應用:
// Unity 實例化對象
Instantiate(prefab, position: spawnPoint.position,rotation: Quaternion.identity,parent: transform
);// 創建顏色
var color = new Color(r: 0.5f, g: 0.7f, b: 1f);
8. 插值字符串 $
string name = "Alice";
int age = 30;
string message = $"{name} is {age} years old";
功能:
更簡潔的字符串格式化
高級用法:
// 格式控制
$"Price: {price:C2}" // 貨幣格式// 表達式計算
$"Area: {width * height}"// 對齊
$"{"Name",-10} {"Age",5}"
9. 聯合 switch
表達式
var result = operation switch
{"add" => a + b,"sub" => a - b,"mul" => a * b,"div" when b != 0 => a / b,_ => throw new InvalidOperationException()
};
功能:
更簡潔的模式匹配語法
實際應用:
// Unity 狀態處理
currentState = input switch
{InputType.Jump when isGrounded => PlayerState.Jumping,InputType.Attack => PlayerState.Attacking,InputType.Dash when canDash => PlayerState.Dashing,_ => currentState
};
10. 委托合并運算符 +
和 -
event Action OnEvent;void Subscribe()
{OnEvent += Handler1;OnEvent += Handler2;
}void Unsubscribe()
{OnEvent -= Handler1;
}
功能:
管理事件訂閱
實際應用:
// Unity 事件管理
button.onClick.AddListener(OnClick);
// ...
button.onClick.RemoveListener(OnClick);// 多播委托
Action multiAction = MethodA;
multiAction += MethodB;
multiAction(); // 調用 MethodA 和 MethodB
實用技巧:組合使用運算符
// 安全訪問并設置默認值
string username = user?.Profile?.Name ?? "Guest";// 安全訪問數組元素
int? score = scores?[index] ?? 0;// 模式匹配與空檢查
if (obj is Player { Health: > 0 } player)
{player.Respawn();
}
這些運算符雖然相對"冷門",但在實際開發中能極大提升代碼的簡潔性。