赋值运算符 #
一、赋值运算符概述 #
C#提供了以下赋值运算符:
| 运算符 | 示例 | 等价于 |
|---|---|---|
| = | a = b | a = b |
| += | a += b | a = a + b |
| -= | a -= b | a = a - b |
| *= | a *= b | a = a * b |
| /= | a /= b | a = a / b |
| %= | a %= b | a = a % b |
| &= | a &= b | a = a & b |
| |= | a |= b | a = a | b |
| ^= | a ^= b | a = a ^ b |
| <<= | a <<= b | a = a << b |
| >>= | a >>= b | a = a >> b |
| ??= | a ??= b | a = a ?? b |
二、基本赋值运算符 #
2.1 简单赋值 #
csharp
int a = 10;
string name = "张三";
double price = 99.99;
2.2 连续赋值 #
csharp
int a, b, c;
a = b = c = 10;
2.3 声明时赋值 #
csharp
int x = 10, y = 20, z = 30;
var name = "张三";
var numbers = new List<int> { 1, 2, 3 };
三、算术复合赋值 #
3.1 += 运算符 #
csharp
int a = 10;
a += 5;
string s = "Hello";
s += " World";
List<int> list = new List<int>();
list += 1;
3.2 -= 运算符 #
csharp
int a = 10;
a -= 5;
List<int> list = new List<int> { 1, 2, 3 };
list -= 1;
3.3 *= 运算符 #
csharp
int a = 10;
a *= 2;
double price = 99.99;
price *= 0.8;
3.4 /= 运算符 #
csharp
int a = 10;
a /= 2;
double total = 100;
total /= 3;
3.5 %= 运算符 #
csharp
int a = 17;
a %= 5;
四、位运算复合赋值 #
4.1 &= 运算符 #
csharp
int flags = 0b1111;
flags &= 0b1010;
[Flags]
enum Permissions { Read = 1, Write = 2, Execute = 4 }
Permissions perm = Permissions.Read | Permissions.Write;
perm &= ~Permissions.Write;
4.2 |= 运算符 #
csharp
int flags = 0b1000;
flags |= 0b0010;
Permissions perm = Permissions.Read;
perm |= Permissions.Write;
4.3 ^= 运算符 #
csharp
int flags = 0b1010;
flags ^= 0b0010;
4.4 <<= 和 >>= 运算符 #
csharp
int a = 5;
a <<= 2;
int b = 20;
b >>= 2;
五、空值合并赋值运算符 #
5.1 ??= 运算符(C# 8+) #
csharp
string name = null;
name ??= "默认名称";
List<int> list = null;
list ??= new List<int>();
list.Add(1);
5.2 与 ?? 运算符对比 #
csharp
string name = null;
name = name ?? "默认名称";
name ??= "默认名称";
5.3 应用场景 #
csharp
public class Cache
{
private Dictionary<string, string> _data;
public string Get(string key)
{
_data ??= new Dictionary<string, string>();
if (!_data.TryGetValue(key, out var value))
{
value = LoadFromDatabase(key);
_data[key] = value;
}
return value;
}
}
六、赋值表达式 #
6.1 赋值作为表达式 #
csharp
int a;
int b = (a = 10) + 5;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
if ((result = Calculate()) > 0)
{
Console.WriteLine(result);
}
6.2 在循环中使用 #
csharp
int sum = 0;
int i = 0;
while ((i += 1) <= 10)
{
sum += i;
}
6.3 在条件中使用 #
csharp
string input;
if (!string.IsNullOrEmpty(input = Console.ReadLine()))
{
Console.WriteLine($"输入:{input}");
}
七、ref赋值(C# 7.3+) #
7.1 ref局部变量 #
csharp
int[] numbers = { 1, 2, 3, 4, 5 };
ref int refToSecond = ref numbers[1];
refToSecond = 20;
Console.WriteLine(numbers[1]);
7.2 ref条件赋值 #
csharp
int a = 10;
int b = 20;
ref int larger = ref (a > b ? ref a : ref b);
larger = 100;
八、目标类型new表达式(C# 9+) #
8.1 类型推断 #
csharp
List<int> numbers = new();
Dictionary<string, int> dict = new();
Person person = new() { Name = "张三", Age = 25 };
8.2 方法参数 #
csharp
void Process(List<int> numbers) { }
Process(new());
Process(new() { 1, 2, 3 });
九、实战示例 #
9.1 累加器 #
csharp
public class Accumulator
{
private int _sum = 0;
private int _count = 0;
public void Add(int value)
{
_sum += value;
_count += 1;
}
public double Average => _count > 0 ? (double)_sum / _count : 0;
}
9.2 配置管理 #
csharp
public class Configuration
{
private string _connectionString;
private int _timeout = 30;
private bool _enableLogging;
public void SetConnectionString(string connectionString)
{
_connectionString ??= connectionString;
}
public void Configure(int? timeout = null, bool? enableLogging = null)
{
if (timeout.HasValue)
_timeout = timeout.Value;
_enableLogging = enableLogging ?? _enableLogging;
}
}
9.3 缓存实现 #
csharp
public class LazyCache<T>
{
private T _value;
private readonly Func<T> _factory;
private bool _initialized;
public LazyCache(Func<T> factory)
{
_factory = factory;
}
public T Value
{
get
{
if (!_initialized)
{
_value = _factory();
_initialized = true;
}
return _value;
}
}
}
十、注意事项 #
10.1 类型兼容性 #
csharp
int a = 10;
a += 5.5;
double d = 10.5;
d += 5;
10.2 溢出检查 #
csharp
checked
{
int max = int.MaxValue;
max += 1;
}
10.3 空值处理 #
csharp
int? a = null;
a += 10;
string s = null;
s += "Hello";
十一、总结 #
赋值运算符要点:
| 运算符 | 说明 |
|---|---|
| = | 基本赋值 |
| += -= *= /= %= | 算术复合赋值 |
| &= |= ^= <<= >>= | 位运算复合赋值 |
| ??= | 空值合并赋值 |
下一步,让我们学习运算符优先级!
最后更新:2026-03-26