类型转换 #
一、类型转换概述 #
C#中的类型转换分为以下几种:
| 类型 | 说明 |
|---|---|
| 隐式转换 | 自动进行,安全转换 |
| 显式转换 | 需要强制转换,可能丢失数据 |
| 用户定义转换 | 自定义类型的转换方法 |
| 辅助类转换 | 使用Convert、Parse等方法 |
二、隐式转换 #
2.1 数值类型隐式转换 #
从小类型到大类型自动转换:
csharp
byte b = 10;
short s = b;
int i = s;
long l = i;
float f = l;
double d = f;
转换规则:
text
byte → short → int → long → float → double
↓
sbyte
↓
short → int → long → float → double
char → int → long → float → double
2.2 隐式转换示例 #
csharp
int intValue = 100;
long longValue = intValue;
float floatValue = 3.14f;
double doubleValue = floatValue;
char charValue = 'A';
int charToInt = charValue;
2.3 可空类型隐式转换 #
csharp
int number = 10;
int? nullableNumber = number;
三、显式转换 #
3.1 强制类型转换 #
csharp
double d = 123.456;
int i = (int)d;
long l = 1000L;
int j = (int)l;
float f = 3.99f;
int k = (int)f;
注意:可能丢失数据
csharp
double d = 123.999;
int i = (int)d;
long bigNumber = 3000000000L;
int overflow = (int)bigNumber;
3.2 checked关键字 #
检查溢出:
csharp
checked
{
int max = int.MaxValue;
int overflow = max + 1;
}
int result = checked((int)bigNumber);
3.3 unchecked关键字 #
忽略溢出检查:
csharp
unchecked
{
int max = int.MaxValue;
int overflow = max + 1;
}
四、Parse方法 #
4.1 基本用法 #
将字符串转换为对应类型:
csharp
int number = int.Parse("123");
double price = double.Parse("3.14");
bool flag = bool.Parse("true");
DateTime date = DateTime.Parse("2024-01-01");
4.2 Parse异常 #
字符串格式不正确会抛出异常:
csharp
try
{
int number = int.Parse("abc");
}
catch (FormatException ex)
{
Console.WriteLine($"格式错误:{ex.Message}");
}
4.3 带格式的Parse #
csharp
int number = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);
double value = double.Parse("1,234.56", CultureInfo.InvariantCulture);
DateTime date = DateTime.ParseExact("2024-01-01", "yyyy-MM-dd", null);
五、TryParse方法 #
5.1 安全转换 #
TryParse不会抛出异常,返回bool表示是否成功:
csharp
string input = "123";
if (int.TryParse(input, out int number))
{
Console.WriteLine($"转换成功:{number}");
}
else
{
Console.WriteLine("转换失败");
}
5.2 各类型的TryParse #
csharp
bool intSuccess = int.TryParse("123", out int intResult);
bool doubleSuccess = double.TryParse("3.14", out double doubleResult);
bool boolSuccess = bool.TryParse("true", out bool boolResult);
bool dateSuccess = DateTime.TryParse("2024-01-01", out DateTime dateResult);
5.3 实际应用 #
csharp
Console.Write("请输入年龄:");
string input = Console.ReadLine();
if (int.TryParse(input, out int age) && age > 0 && age < 150)
{
Console.WriteLine($"您的年龄是:{age}");
}
else
{
Console.WriteLine("请输入有效的年龄");
}
六、Convert类 #
6.1 常用方法 #
csharp
int i = Convert.ToInt32("123");
double d = Convert.ToDouble("3.14");
bool b = Convert.ToBoolean("true");
string s = Convert.ToString(123);
6.2 Convert方法列表 #
| 方法 | 说明 |
|---|---|
| ToBoolean | 转换为bool |
| ToByte | 转换为byte |
| ToChar | 转换为char |
| ToDateTime | 转换为DateTime |
| ToDecimal | 转换为decimal |
| ToDouble | 转换为double |
| ToInt16 | 转换为short |
| ToInt32 | 转换为int |
| ToInt64 | 转换为long |
| ToSByte | 转换为sbyte |
| ToSingle | 转换为float |
| ToString | 转换为string |
| ToUInt16 | 转换为ushort |
| ToUInt32 | 转换为uint |
| ToUInt64 | 转换为ulong |
6.3 进制转换 #
csharp
int number = 255;
string binary = Convert.ToString(number, 2);
string octal = Convert.ToString(number, 8);
string hex = Convert.ToString(number, 16);
int fromBinary = Convert.ToInt32("11111111", 2);
int fromHex = Convert.ToInt32("FF", 16);
6.4 Convert vs Parse #
| 特性 | Convert | Parse |
|---|---|---|
| null处理 | 返回默认值 | 抛出异常 |
| 异常 | 格式错误抛异常 | 格式错误抛异常 |
| 适用场景 | 通用转换 | 字符串转类型 |
csharp
int result1 = Convert.ToInt32("123");
int result2 = int.Parse("123");
int result3 = Convert.ToInt32(null);
七、装箱与拆箱 #
7.1 装箱 #
值类型转换为引用类型:
csharp
int number = 42;
object boxed = number;
7.2 拆箱 #
引用类型转换为值类型:
csharp
object boxed = 42;
int number = (int)boxed;
7.3 性能影响 #
装箱和拆箱有性能开销:
csharp
var list = new ArrayList();
for (int i = 0; i < 1000000; i++)
{
list.Add(i);
}
var genericList = new List<int>();
for (int i = 0; i < 1000000; i++)
{
genericList.Add(i);
}
7.4 避免装箱 #
使用泛型代替:
csharp
public void ProcessValue(object value)
{
int number = (int)value;
}
public void ProcessValue<T>(T value)
{
}
八、类型转换运算符 #
8.1 as运算符 #
安全的引用类型转换:
csharp
object obj = "Hello";
string str = obj as string;
if (str != null)
{
Console.WriteLine(str);
}
8.2 is运算符 #
检查类型并转换(C# 7+):
csharp
object obj = "Hello";
if (obj is string str)
{
Console.WriteLine(str.Length);
}
if (obj is int number)
{
Console.WriteLine(number);
}
8.3 模式匹配 #
csharp
object value = 42;
string result = value switch
{
int i => $"整数:{i}",
double d => $"浮点数:{d}",
string s => $"字符串:{s}",
null => "null",
_ => "未知类型"
};
九、自定义类型转换 #
9.1 隐式转换运算符 #
csharp
public class Celsius
{
public double Degrees { get; }
public Celsius(double degrees)
{
Degrees = degrees;
}
public static implicit operator Fahrenheit(Celsius c)
{
return new Fahrenheit(c.Degrees * 9 / 5 + 32);
}
}
public class Fahrenheit
{
public double Degrees { get; }
public Fahrenheit(double degrees)
{
Degrees = degrees;
}
public static implicit operator Celsius(Fahrenheit f)
{
return new Celsius((f.Degrees - 32) * 5 / 9);
}
}
Celsius c = new Celsius(25);
Fahrenheit f = c;
9.2 显式转换运算符 #
csharp
public class Money
{
public decimal Amount { get; }
public Money(decimal amount)
{
Amount = amount;
}
public static explicit operator decimal(Money m)
{
return m.Amount;
}
public static explicit operator Money(decimal d)
{
return new Money(d);
}
}
Money money = new Money(100.50m);
decimal amount = (decimal)money;
十、类型转换最佳实践 #
10.1 选择合适的方法 #
| 场景 | 推荐方法 |
|---|---|
| 字符串转数值 | TryParse |
| 安全类型检查 | is/as |
| 通用转换 | Convert |
| 用户输入处理 | TryParse |
10.2 处理用户输入 #
csharp
public int? GetValidNumber(string input)
{
if (int.TryParse(input, out int result))
{
return result;
}
return null;
}
public bool TryGetNumber(string input, out int number)
{
number = 0;
if (string.IsNullOrWhiteSpace(input))
return false;
return int.TryParse(input, out number);
}
10.3 避免常见错误 #
csharp
string input = "123.45";
int wrong = int.Parse(input);
if (double.TryParse(input, out double d))
{
int correct = (int)d;
}
十一、总结 #
类型转换要点:
| 方法 | 说明 |
|---|---|
| 隐式转换 | 自动安全转换 |
| 显式转换 | 强制转换 |
| Parse | 字符串解析 |
| TryParse | 安全解析 |
| Convert | 通用转换 |
| as/is | 引用类型转换 |
下一步,让我们学习字符串操作!
最后更新:2026-03-26