## 一、整型之间的类型转换
详细介绍C#中整数类型之间的数据类型转换。
C#中的整数类型主要包括byte
, sbyte
, short
, ushort
, int
, uint
, long
, ulong
。
## 整数类型范围对比
首先了解各整数类型的取值范围:
| 类型 | 大小 | 范围 | 说明 |
|------|------|------|------|
| sbyte
| 8位 | -128 到 127 | 有符号字节 |
| byte
| 8位 | 0 到 255 | 无符号字节 |
| short
| 16位 | -32,768 到 32,767 | 有符号短整型 |
| ushort
| 16位 | 0 到 65,535 | 无符号短整型 |
| int
| 32位 | -2,147,483,648 到 2,147,483,647 | 有符号整型 |
| uint
| 32位 | 0 到 4,294,967,295 | 无符号整型 |
| long
| 64位 | -9.2×10¹⁸ 到 9.2×10¹⁸ | 有符号长整型 |
| ulong
| 64位 | 0 到 1.8×10¹⁹ | 无符号长整型 |
#### 1. 1隐式转换(Implicit Conversion)
**规则:** 从小范围类型向大范围类型转换,且不会丢失数据时,可以隐式转换。
示例:安全的隐式转换
```csharp
// byte → short → int → long (无符号到有符号的扩大)
byte b = 200;
short s = b; // 隐式转换:byte → short
int i = s; // 隐式转换:short → int
long l = i; // 隐式转换:int → long
Console.WriteLine($"byte {b} → short {s} → int {i} → long {l}");
// sbyte → short → int → long (有符号到有符号的扩大)
sbyte sb = -100;
short s2 = sb; // 隐式转换
int i2 = s2; // 隐式转换
long l2 = i2; // 隐式转换
// ushort → uint → ulong (无符号到无符号的扩大)
ushort us = 40000;
uint ui = us; // 隐式转换
ulong ul = ui; // 隐式转换
// 相同大小但有符号→无符号?不可以隐式!
// int x = 100;
// uint y = x; // 编译错误:不能隐式转换
```
#### 1.2. 显式转换(Explicit Conversion)
**规则:** 从大范围类型向小范围类型转换,或在不同符号类型之间转换时,需要显式转换。
示例:需要显式转换的情况
```csharp
// int → short → byte (缩小转换 - 可能数据丢失)
int largeInt = 1000;
short smallShort = (short)largeInt; // 显式转换:1000
byte smallByte = (byte)largeInt; // 显式转换:232 (1000 % 256)
Console.WriteLine($"int {largeInt} → short {(short)largeInt} → byte {(byte)largeInt}");
// 有符号 ↔ 无符号转换
int signed = -50;
uint unsigned = (uint)signed; // 显式转换:4294967246
Console.WriteLine($"int {signed} → uint {(uint)signed}");
uint positive = 300;
int signed2 = (int)positive; // 显式转换:300
Console.WriteLine($"uint {positive} → int {(int)positive}");
// long → int (大范围到小范围)
long bigLong = 2_000_000_000;
int normalInt = (int)bigLong; // 2000000000 (在int范围内)
long tooBig = 3_000_000_000;
int overflow = (int)tooBig; // -1294967296 (溢出)
Console.WriteLine($"long {tooBig} → int {(int)tooBig} (溢出)");
```
#### 1.3. 使用 Convert 类进行转换
Convert
类提供更安全的转换方式,会进行范围检查并在溢出时抛出异常。
```csharp
// 使用Convert类进行整数转换
int number = 255;
// 成功转换
byte b1 = Convert.ToByte(number); // 255
short s1 = Convert.ToInt16(number); // 255
// 溢出时会抛出异常
try
{
int tooBig = 1000;
byte b2 = Convert.ToByte(tooBig); // 抛出 OverflowException
}
catch (OverflowException ex)
{
Console.WriteLine($"转换溢出: {ex.Message}");
}
// 处理null值
int? nullableInt = null;
int result = Convert.ToInt32(nullableInt); // 返回 0
```
### 2.浮点数之间
```c#
// float ↔ double ↔ decimal
float floatValue = 3.14f;
double doubleValue = 2.71828;
decimal decimalValue = 123.456m;
// 需要显式转换(可能精度丢失)
double fromFloat = floatValue; // 隐式:3.14
float fromDouble = (float)doubleValue; // 显式:2.71828(可能精度损失)
decimal fromDouble2 = (decimal)doubleValue; // 显式:2.71828
// decimal 与其他浮点数的转换都需要显式
double fromDecimal = (double)decimalValue; // 123.456
float fromDecimal2 = (float)decimalValue; // 123.456f
```
### 3.整数和浮点数之间
## 二、数值和字符串
```c#
// string → double
string doubleStr = "3.14159";
double d1 = double.Parse(doubleStr); // 3.14159
double d2 = Convert.ToDouble("123.45"); // 123.45
double.TryParse("invalid", out double d3); // d3 = 0, 返回false
// string → float
string floatStr = "2.718f";
float f1 = float.Parse(floatStr); // 2.718
float f2 = Convert.ToSingle("99.99"); // 99.99f
// string → decimal (适合金融计算)
string moneyStr = "2999.99";
decimal m1 = decimal.Parse(moneyStr); // 2999.99m
decimal m2 = Convert.ToDecimal("0.1"); // 0.1m
// 数值 → string (所有数值类型都适用)
int number = 42;
double price = 19.95m;
string str1 = number.ToString(); // "42"
string str2 = price.ToString("C2"); // "$19.95" (货币格式)
string str3 = $"{123.456:F1}"; // "123.5" (插值字符串)
```
## 三、数值 和 字符
```c#
// char → int (获取ASCII码)
char letter = 'A';
int ascii = (int)letter; // 65
int unicode = letter; // 65 (隐式转换)
// int → char (根据ASCII码获取字符)
int code = 66;
char character = (char)code; // 'B'
// char → string
char ch = 'X';
string charStr = ch.ToString(); // "X"
string charStr2 = $"{ch}"; // "X"
```
## 四、数值 和 布尔值
## 五、字符串 和 布尔值
```c#
// string → bool
string trueStr = "True";
string falseStr = "False";
bool b1 = bool.Parse(trueStr); // true
bool b2 = Convert.ToBoolean("true"); // true (不区分大小写)
bool b3 = Convert.ToBoolean("1"); // true (将"1"视为true)
bool b4 = Convert.ToBoolean("0"); // false (将"0"视为false)
// bool → string
bool isValid = true;
string boolStr1 = isValid.ToString(); // "True"
string boolStr2 = $"{false}"; // "False"
```
## 六、字符串 和 日期
```c#
// string → DateTime
string dateStr = "2024-01-15";
string dateTimeStr = "2024-01-15 14:30:00";
DateTime dt1 = DateTime.Parse(dateStr); // 2024/1/15 0:00:00
DateTime dt2 = Convert.ToDateTime("2023/12/25"); // 2023/12/25
DateTime dt3 = DateTime.ParseExact("15-01-2024", "dd-MM-yyyy", null);
// DateTime → string
DateTime now = DateTime.Now;
string dateStr1 = now.ToString(); // "2024/1/15 14:30:45"
string dateStr2 = now.ToString("yyyy-MM-dd"); // "2024-01-15"
string dateStr3 = $"{now:yyyy年MM月dd日}"; // "2024年01月15日"
```
## 七、整数 和 枚举
```c#
public enum Status { Active = 1, Inactive = 0, Pending = 2 }
// enum → int
Status status = Status.Active;
int statusValue = (int)status; // 1
// int → enum
int value = 2;
Status fromInt = (Status)value; // Status.Pending
// string → enum
string statusStr = "Active";
Status fromStr = (Status)Enum.Parse(typeof(Status), statusStr); // Status.Active
// enum → string
string statusText = Status.Inactive.ToString(); // "Inactive"
```
## 练习
好的,这里有20道关于C#数据类型转换的单选题,涵盖了隐式转换、显式转换、Convert类、Parse/TryParse方法以及装箱拆箱等核心概念。
---
**1. 以下哪种转换在C#中属于隐式转换?**
A. int
转换为 long
B. double
转换为 int
C. decimal
转换为 float
D. long
转换为 int
**2. 执行代码 int num = (int)3.14;
后,变量 num
的值是多少?**
A. 3.14
B. 3
C. 4
D. 编译错误
**3. 以下哪个方法最适合安全地将一个字符串(如用户输入)转换为整数?**
A. (int)
B. Convert.ToInt()
C. int.Parse()
D. int.TryParse()
**4. 代码 object obj = 10; int num = (int)obj;
演示了哪种概念?**
A. 装箱
B. 拆箱
C. 隐式转换
D. 接口转换
**5. 表达式 (double)10 / 4
的结果是什么?**
A. 2
B. 2.0
C. 2.5
D. 2.50
**6. Convert.ToInt32(5.6)
的返回值是?**
A. 5
B. 6
C. 5.6
D. 运行时异常
**7. 对于字符串 str = "123"
,以下哪种转换方式会抛出异常?**
A. int.Parse(str)
B. Convert.ToInt32(str)
C. (int)str
D. int.TryParse(str, out int result)
**8. 代码 byte b = 200; int i = b;
执行时会发生什么?**
A. 编译错误
B. 运行时错误
C. 隐式转换成功i
的值为200
D. 需要显式转换int i = (int)b
**9. 以下关于 as
运算符的说法,哪一个是正确的?**
A. 它可以用于任何值类型之间的转换。
B. 如果转换失败,它会返null
。
C. 如果转换失败,它会抛InvalidCastException
异常。
D. 它用于执行隐式转换。
**10. 执行 bool success = int.TryParse("Hello", out int number);
后success
和 number
的值分别是?**
A. true
, 0
B. false
, 0
C. true
, null
D. false
, null
**11. 代码 var result = 5 + 2.5;
中,变量 result
的数据类型是?**
A. int
B. double
C. decimal
D. string
**12. 要将一个可空整数 int? nullableInt
安全地转换为 int
,如果它为 null
则提供默认值0,应使用?**
A. (int)nullableInt
B. nullableInt.Value
C. nullableInt.GetValueOrDefault()
D. Convert.ToInt32(nullableInt)
**13. ToString()
方法实现了什么类型的转换?**
A. 隐式转换
B. 显式转换
C. 装箱
D. 都不是,它是方法调用
**14. 表达式 "5" + 1
在C#中的结果是?**
A. 6
B. "51"
C. "6"
D. 编译错误
**15. 以下哪种转换需要显式地进行(即可能导致精度丢失或运行时检查)?**
A. short
转换为 int
B. int
转换为 short
C. float
转换为 double
D. char
转换为 int
**16. decimal
和 double
之间?**
A. 可以双向隐式转换
B. 可以双向显式转换
C. 只能从 double
显式转换为 decimal
D. 只能从 decimal
显式转换为 double
**17. 代码 dynamic dyn = 100; int num = dyn;
会发生什么?**
A. 编译错误
B. 运行时解析,转换成功
C. 运行时抛出异常
D. 需要显式转换int num = (int)dyn
**18. 对于自定义结构体 MyStruct
,如何定义一个到 int
的显式转换?**
A. public static int explicit operator(MyStruct m) { ... }
B. public static explicit operator int(MyStruct m) { ... }
C. public int ToInt() { ... }
D. 结构体不能定义自定义转换
**19. System.BitConverter
类的主要用途是?**
A. 将基础数据类型与字节数组相互转换
B. 进行高性能的数学计算
C. 转换数字的进制(如十进制转二进制)
D. 处理字符串编码转换
**20. 代码 IEnumerable<int> numbers = new List<int>(); var list = (List<int>)numbers;
可能会抛出异常,更安全的做法是使用?**
A. var list = numbers as List<int>;
B. var list = numbers.ToList();
C. var list = Convert.ChangeType(numbers, typeof(List<int>));
D. var list = (List<int>)(object)numbers;
---
**参考答案:**
1. A
2. B
3. D
4. B
5. C
6. B (四舍六入五取偶,5.6入为6)
7. C
8. C
9. B
10. B
11. B
12. C
13. D
14. B (字符串连接)
15. B
16. B
17. B (动态类型在运行时解析)
18. B
19. A
20. A as
运算符在转换失败时返回 null
而不是抛出异常)