Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 类型转换

作者:青灯寂焚   发布日期:2026-05-04   浏览:105

// C# 类型转换示例

using System;

class Program
{
    static void Main()
    {
        // 隐式类型转换(Implicit Conversion)
        int intValue = 10;
        double doubleValue = intValue; // 整数可以隐式转换为双精度浮点数
        Console.WriteLine("隐式类型转换: " + doubleValue);

        // 显式类型转换(Explicit Conversion)
        double doubleValue2 = 10.5;
        int intValue2 = (int)doubleValue2; // 双精度浮点数需要显式转换为整数
        Console.WriteLine("显式类型转换: " + intValue2); // 注意:这里会丢失小数部分

        // 使用 Convert 类进行类型转换
        string strValue = "123";
        int convertedInt = Convert.ToInt32(strValue);
        Console.WriteLine("使用 Convert 类转换: " + convertedInt);

        // 使用 TryParse 方法进行安全的类型转换
        string strValue2 = "456";
        if (int.TryParse(strValue2, out intValue2))
        {
            Console.WriteLine("TryParse 成功: " + intValue2);
        }
        else
        {
            Console.WriteLine("TryParse 失败");
        }

        // 使用 as 关键字进行引用类型之间的安全转换
        object obj = "Hello World";
        string strObj = obj as string;
        if (strObj != null)
        {
            Console.WriteLine("as 关键字转换成功: " + strObj);
        }
        else
        {
            Console.WriteLine("as 关键字转换失败");
        }
    }
}

解释说明:

  1. 隐式类型转换:不需要显式地指定转换操作,编译器自动处理。例如,将 int 转换为 double
  2. 显式类型转换:需要显式地指定转换操作,可能会导致数据丢失或异常。例如,将 double 转换为 int 时会丢失小数部分。
  3. 使用 Convert:提供了多种类型的转换方法,适用于常见的类型转换需求。
  4. 使用 TryParse 方法:用于安全地将字符串转换为数值类型,避免抛出异常。
  5. 使用 as 关键字:用于引用类型之间的安全转换,如果转换失败则返回 null

上一篇:c# string format

下一篇:c# base64解码

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站