C# - 赋值运算符
C# - 赋值运算符
Section titled “C# - 赋值运算符”在 C# 中,赋值运算符用于为变量赋值。最基本的运算符是简单赋值运算符(=)。C# 还提供了一组复合赋值运算符,它们将算术或位运算与赋值结合起来,提供了更简洁的语法。
赋值运算符列表
Section titled “赋值运算符列表”下表列出了 C# 中可用的赋值运算符。
| 运算符 | 示例 | 等效于 |
|---|---|---|
简单赋值(=) | x = y | x = y |
加法赋值(+=) | x += y | x = x + y |
减法赋值(-=) | x -= y | x = x - y |
乘法赋值(*=) | x *= y | x = x * y |
除法赋值(/=) | x /= y | x = x / y |
取模赋值(%=) | x %= y | x = x % y |
按位与赋值(&=) | x &= y | x = x & y |
按位或赋值(|=) | x |= y | x = x | y |
按位异或赋值(^=) | x ^= y | x = x ^ y |
左移赋值(<<=) | x <<= y | x = x << y |
右移赋值(>>=) | x >>= y | x = x >> y |
空合并赋值(??=) | x ??= y | if (x == null) x = y; |
常见赋值运算符示例
Section titled “常见赋值运算符示例”让我们通过清晰的现代代码示例来探究最常用的运算符。
using System;
// 1. 简单赋值 (=)int score = 100;Console.WriteLine($"Initial score: {score}");
// 2. 加法赋值 (+=)score += 50; // Player earned 50 pointsConsole.WriteLine($"Score after adding points: {score}"); // 150
// 3. 减法赋值 (-=)int health = 100;health -= 25; // Player took 25 damageConsole.WriteLine($"Health after taking damage: {health}"); // 75
// 4. 乘法赋值 (*=)double investment = 1000.0;investment *= 1.05; // Investment grew by 5%Console.WriteLine($"Investment value after growth: {investment:C}"); // $1,050.00
// 5. 除法赋值 (/=)int totalItems = 100;totalItems /= 2; // Half of the items were soldConsole.WriteLine($"Remaining items: {totalItems}"); // 50
// 6. 取模赋值 (%)int itemIndex = 12;int itemsPerPage = 10;itemIndex %= itemsPerPage; // Get the index on the current pageConsole.WriteLine($"Item index on page: {itemIndex}"); // 2空合并赋值运算符(??=)
Section titled “空合并赋值运算符(??=)”??= 运算符在 C# 8.0 中引入,它提供了一种简洁的方式,仅当变量为 null 时才为其赋值。这对于延迟初始化(lazy initialization)和设置默认值非常有用。
示例 1:设置默认值
Section titled “示例 1:设置默认值”using System;using System.Collections.Generic;
List<string>? names = null;
// 如果 'names' 为 null,则创建一个新列表并赋值给它。// 如果它不为 null,则此行不执行任何操作。names ??= new List<string>();
names.Add("Alice");Console.WriteLine($"List contains: {string.Join(", ", names)}");示例 2:类中的延迟初始化
Section titled “示例 2:类中的延迟初始化”这种模式对性能很有利,因为昂贵的(资源消耗大的)对象创建只在首次需要时发生。
public class ExpensiveService{ public ExpensiveService() { Console.WriteLine("--> ExpensiveService instance created."); }}
public class ServiceProvider{ private ExpensiveService? _service;
public ExpensiveService GetService() { // 服务只在首次调用 GetService() 时实例化。 _service ??= new ExpensiveService(); return _service; }}
// --- 用法 ---var provider = new ServiceProvider();Console.WriteLine("Provider created. Service not yet initialized.");
var s1 = provider.GetService(); // 此处打印 "--> ExpensiveService instance created."var s2 = provider.GetService(); // 不会打印任何内容,返回现有实例最佳实践与注意事项
Section titled “最佳实践与注意事项”- 清晰简洁:使用复合赋值运算符(如
+=和-=)可以使你的代码更具可读性和简洁性,特别是用于递增计数器或累加值时。 - 类型安全:注意隐式类型转换。例如,如果你使用
/=将一个整数除以另一个整数,结果将是整数,任何小数部分都将被丢弃。int x = 5; x /= 2;的结果是x等于2。 - 除以零:在使用
/=或%=之前,确保右侧的操作数不为零,以避免DivideByZeroException。 - 运算符优先级:请记住,赋值运算符的优先级非常低。在复杂的表达式中,它们最后被求值。使用括号来确保运算顺序符合你的意图。
- 使用
??=设置默认值:推荐使用??=运算符来设置默认值和进行延迟初始化。它比if (x == null)检查更具表达性,且不易出错。