C# 类型转换与运算符

4.1 隐式类型转换

隐式转换是安全的,不会丢失数据,编译器自动执行。

数值隐式转换

1
2
3
4
5
6
7
8
9
10
11
// 小范围 → 大范围
byte b = 100;
short s = b; // byte → short
int i = s; // short → int
long l = i; // int → long
float f = l; // long → float
double d = f; // float → double

// int 可以隐式转换为 double
int x = 10;
double y = x; // 10.0

转换规则

1
2
3
byte → short → int → long → float → double

char → int ──────────────────────┘

4.2 显式类型转换(强制转换)

显式转换可能丢失数据,需要使用强制转换语法。

数值强制转换

1
2
3
4
5
6
7
8
9
10
11
double d = 3.14;
int i = (int)d; // 3(小数部分丢失)

long l = 10000000000L;
int x = (int)l; // 可能溢出

// 检查溢出
checked
{
int y = (int)l; // 溢出时抛出 OverflowException
}

Convert 类

1
2
3
4
5
6
7
8
string text = "123";
int number = Convert.ToInt32(text); // 123
double pi = Convert.ToDouble("3.14"); // 3.14
bool flag = Convert.ToBoolean("true"); // True

// 其他类型
string str = Convert.ToString(42); // "42"
DateTime dt = Convert.ToDateTime("2024-01-01");

4.3 Parse 与 TryParse

Parse 方法

1
2
3
4
5
6
int a = int.Parse("100");           // 100
double b = double.Parse("3.14"); // 3.14
bool c = bool.Parse("True"); // True

// 格式错误会抛出异常
// int x = int.Parse("abc"); // FormatException

TryParse 方法(推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 安全解析,不会抛出异常
if (int.TryParse("123", out int result1))
{
Console.WriteLine($"解析成功: {result1}"); // 123
}

if (int.TryParse("abc", out int result2))
{
Console.WriteLine("不会执行");
}
else
{
Console.WriteLine("解析失败");
}

// 一行写法
bool success = int.TryParse("456", out int value);

4.4 算术运算符

运算符 说明 示例 结果
+ 加法 10 + 3 13
- 减法 10 - 3 7
* 乘法 10 * 3 30
/ 除法 10 / 3 3(整数除法)
% 取余 10 % 3 1
++ 自增 x++++x x + 1
-- 自减 x----x x - 1

除法注意

1
2
3
4
5
6
7
8
// 整数除法
int a = 10 / 3; // 3(截断小数)

// 浮点除法
double b = 10.0 / 3; // 3.33333333333333

// 强制浮点除法
double c = (double)10 / 3; // 3.33333333333333

自增自减

1
2
3
4
5
6
7
8
9
int x = 5;

// 后置:先使用,后自增
int y = x++; // y = 5, x = 6

// 前置:先自增,后使用
int z = ++x; // x = 7, z = 7

Console.WriteLine($"x={x}, y={y}, z={z}");

4.5 关系运算符

运算符 说明 示例 结果
== 等于 5 == 5 true
!= 不等于 5 != 3 true
> 大于 5 > 3 true
< 小于 5 < 3 false
>= 大于等于 5 >= 5 true
<= 小于等于 5 <= 3 false

示例

1
2
3
4
5
6
7
8
int age = 20;

Console.WriteLine(age == 20); // True
Console.WriteLine(age != 20); // False
Console.WriteLine(age > 18); // True
Console.WriteLine(age < 18); // False
Console.WriteLine(age >= 20); // True
Console.WriteLine(age <= 20); // True

4.6 逻辑运算符

运算符 说明 示例 结果
&& 逻辑与 true && false false
|| 逻辑或 true || false true
! 逻辑非 !true false

短路求值

1
2
3
4
5
// && 短路:第一个为 false 时不计算第二个
bool result1 = false && CheckExpensive(); // CheckExpensive 不执行

// || 短路:第一个为 true 时不计算第二个
bool result2 = true || CheckExpensive(); // CheckExpensive 不执行

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int age = 25;
bool hasTicket = true;

// 逻辑与
if (age >= 18 && hasTicket)
{
Console.WriteLine("可以入场");
}

// 逻辑或
bool isWeekend = day == 6 || day == 7;

// 逻辑非
bool isEmpty = !hasItems;

4.7 位运算符

运算符 说明 示例 结果
& 按位与 5 & 3 1
| 按位或 5 | 3 7
^ 按位异或 5 ^ 3 6
~ 按位取反 ~5 -6
<< 左移 5 << 1 10
>> 右移 5 >> 1 2

示例

1
2
3
4
5
6
7
8
int a = 5;   // 0000 0101
int b = 3; // 0000 0011

Console.WriteLine(a & b); // 1 (0000 0001)
Console.WriteLine(a | b); // 7 (0000 0111)
Console.WriteLine(a ^ b); // 6 (0000 0110)
Console.WriteLine(a << 1); // 10 (0000 1010)
Console.WriteLine(a >> 1); // 2 (0000 0010)

4.8 赋值运算符

运算符 示例 等价于
= x = 10 x = 10
+= x += 5 x = x + 5
-= x -= 5 x = x - 5
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5
%= x %= 5 x = x % 5
&= x &= 5 x = x & 5
|= x |= 5 x = x | 5

示例

1
2
3
4
5
6
7
int x = 10;

x += 5; // x = 15
x -= 3; // x = 12
x *= 2; // x = 24
x /= 4; // x = 6
x %= 4; // x = 2

4.9 其他运算符

三元运算符

1
2
3
4
5
6
7
8
9
int age = 20;
string status = age >= 18 ? "成年" : "未成年";
Console.WriteLine(status); // 成年

// 等价于
if (age >= 18)
status = "成年";
else
status = "未成年";

null 相关运算符

1
2
3
4
5
6
7
8
9
10
string? name = null;

// null 合并 ??
string displayName = name ?? "匿名用户";

// null 条件 ?.
int? length = name?.Length;

// null 条件索引 ?[]
char? first = name?[0];

is 与 as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
object obj = "Hello";

// is 类型检查
if (obj is string)
{
Console.WriteLine("是字符串");
}

// is 模式匹配(C# 7+)
if (obj is string s)
{
Console.WriteLine(s.Length);
}

// as 安全转换
string text = obj as string; // 失败返回 null

sizeof 与 typeof

1
2
3
4
5
Console.WriteLine(sizeof(int));      // 4
Console.WriteLine(sizeof(double)); // 8

Type t = typeof(int);
Console.WriteLine(t.Name); // Int32

4.10 运算符优先级

从高到低:

优先级 运算符
最高 ++ -- () .
* / %
+ -
< > <= >=
== !=
&&
最低 ||

使用括号明确优先级

1
2
3
4
5
6
// 不推荐
int result = 10 + 5 * 2; // 20

// 推荐
int result = 10 + (5 * 2); // 20
int result = (10 + 5) * 2; // 30

4.11 本章小结

  • 隐式转换安全,显式转换可能丢失数据
  • Convert 类和 Parse/TryParse 用于字符串转换
  • 算术运算符:+ - * / % ++ --
  • 关系运算符返回布尔值
  • 逻辑运算符:&& \|\| !,支持短路求值
  • 三元运算符:条件 ? 值 1 : 值 2
  • 使用括号明确运算优先级

练习题

  1. 将字符串 "123.45" 转换为 double 并加 100
  2. 使用三元运算符判断奇偶数
  3. 使用 TryParse 安全解析用户输入
  4. 以下代码输出什么?
    1
    2
    3
    int x = 5;
    int y = x++ + ++x;
    Console.WriteLine(y);
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
分享: