C# 类型转换(Type Conversion)详解
                           
天天向上
发布: 2025-04-06 23:30:12

原创
964 人浏览过

以下是C# 类型转换(Type Conversion)的完整、系统、专业讲解。内容结构清晰,涵盖了隐式转换、显式转换、系统类(如 Convert)、as/is 运算符、用户自定义转换运算符、以及可空类型转换等,附带示例代码,方便实践与深入理解。


📑 目录导航

  1. 类型转换总览
  2. 隐式类型转换(Implicit Conversion)
  3. 显式类型转换(Explicit Conversion)
  4. Convert 类转换
  5. Parse()TryParse() 方法
  6. asis 运算符
  7. 可空类型转换(Nullable Type Conversion)
  8. 自定义类型转换(Operator Overloading)
  9. 官方文档参考

1️⃣ 类型转换总览

类型转换是将一种数据类型转换为另一种类型的过程。在 C# 中,转换可分为以下几种方式:

类型示例方式说明
隐式转换int -> long小范围 → 大范围(安全)
显式转换(强制)(int)double大范围 → 小范围(可能丢失精度)
使用 ConvertConvert.ToInt32("123")用于字符串和基本类型之间转换
使用 Parse() 方法int.Parse("123")将字符串转换为基本类型
使用 TryParse() 方法int.TryParse("123", out x)转换失败不会抛异常
类型判断与转换is, as, .GetType()判断/转换引用类型
可空类型转换int? -> intNull 值类型转换处理

2️⃣ 隐式转换(Implicit Conversion)

自动完成,不需要额外语法支持。

✅ 适用于:

  • 小容量 → 大容量 类型(如 intlong
  • 派生类 → 基类
  • 非空类型 → 可空类型(intint?
int i = 100;
long l = i; // 隐式转换

float f = 3.5f;
double d = f; // float → double

🔗 官方文档:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit


3️⃣ 显式转换(Explicit Conversion)

需要强制使用 强制转换运算符((T)

double d = 123.45;
int i = (int)d;  // i = 123,丢失小数部分

⚠️ 注意:如果值超出目标类型范围,会发生数据截断或溢出

你也可以使用 checked 检查溢出:

checked
{
    int x = (int)2147483648L; // 抛出 OverflowException
}

🔗 官方文档:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/explicit


4️⃣ 使用 Convert 类转换(System.Convert)

用于任何基本类型之间的转换(包括 stringbool)。

string str = "123";
int i = Convert.ToInt32(str); // i = 123

bool b = Convert.ToBoolean("true");

✔️ 特点:可处理 null 和异常,适用于更广泛的转换。

🔗 官方文档:
https://learn.microsoft.com/en-us/dotnet/api/system.convert


5️⃣ 使用 Parse() 与 TryParse() 方法

Parse() 方法(抛出异常)

string str = "123";
int num = int.Parse(str); // 正常
int invalid = int.Parse("abc"); // 抛出 FormatException

TryParse() 方法(推荐)

string input = "456";
if (int.TryParse(input, out int result))
{
    Console.WriteLine("成功:" + result);
}
else
{
    Console.WriteLine("失败");
}

🔗 官方文档:
https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse


6️⃣ asis 运算符

用于 引用类型转换,避免运行时异常。

🔹 is:类型判断

object obj = "hello";
if (obj is string)
{
    Console.WriteLine("obj 是 string 类型");
}

🔹 as:尝试转换,失败返回 null

object obj = "world";
string str = obj as string; // 成功

🔗 官方文档:


7️⃣ 可空类型转换(Nullable Type Conversion)

✅ 从 TT?

int x = 10;
int? y = x; // 自动转换

✅ 从 T?T

需要判断是否为 null

int? a = null;
int b = a ?? 0; // 如果 a 是 null,则 b = 0

🔗 官方文档:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types


8️⃣ 自定义类型转换运算符(Operator Overloading)

你可以在自定义类中定义隐式或显式转换:

class Celsius
{
    public float Degrees;
    public Celsius(float degrees) => Degrees = degrees;

    public static implicit operator Fahrenheit(Celsius c)
    {
        return new Fahrenheit((9.0f / 5) * c.Degrees + 32);
    }
}

class Fahrenheit
{
    public float Degrees;
    public Fahrenheit(float degrees) => Degrees = degrees;
}

🔗 官方文档:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators


总结表格

类型转换方式是否安全是否抛异常用途
隐式转换✅ 安全❌ 不抛异常小 → 大范围
显式转换(强制)⚠️ 可能丢失❌ 不抛异常大 → 小范围
Convert✅ 安全✅ 会抛异常常用系统类型转换
Parse()⚠️ 不安全✅ 会抛异常字符串 → 类型
TryParse()✅ 安全❌ 不抛异常推荐方式,避免错误
as / is✅ 安全❌ 不抛异常引用类型转换
用户自定义转换自定义依实现而定复杂类型间转换

真实权威参考文档

  • 🔗 类型转换概述:https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/type-conversions
  • 🔗 Convert 类:https://learn.microsoft.com/en-us/dotnet/api/system.convert
  • 🔗 Parse / TryParse:https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse
  • 🔗 类型转换操作符:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conversion-operators
发表回复 0

Your email address will not be published. Required fields are marked *