C# 中,数据类型转换(Casting)指的是将一个数据类型的值转换成另一个数据类型。C# 提供了两种主要的类型转换方式:显式转换(Explicit Casting)和隐式转换(Implicit Casting)。本文主要介绍一下C# 数据类型转换(Casting)。

1、C# 类型转换

类型转换是将一种数据类型的值分配给另一种类型时的类型转换。

在C#中,有两种类型的转换:

  • 隐式转换,自动转换(自动)-将较小的类型转换为较大的类型

byte -> short -> char -> int -> long -> float -> double

  •  显式转换,强制转换(手动)-将较大的类型转换为较小的类型

double -> float -> long -> int -> char -> short -> byte

2、隐式转换(Implicit Casting)

隐式转换是编译器自动完成的类型转换,通常发生在较小的数据类型转换为较大的数据类型时。无需显式地使用强制转换操作符。

例如:

int myInt = 9;
double myDouble = myInt; // 自动转换: int 转换成 double

Console.WriteLine(myInt);      // 输出 9
Console.WriteLine(myDouble);   // 输出 9.0

3、显式转换(Explicit Casting)

显式转换要求开发者手动进行转换,通常发生在较大的数据类型转换为较小的数据类型时,可能会丢失数据,因此需要明确进行强制转换。格式是在需要转型的数据前加上“()”,然后在括号内加入需要转化的数据类型。有的数据经过转型运算后,精度会丢失,而有的会更加精确。

例如:

double myDouble = 9.78;
int myInt = (int) myDouble; // 手动转换: double 转换成 int

Console.WriteLine(myDouble);   // 输出 9.78
Console.WriteLine(myInt);      // 输出 9
int x;
double y;
x = (int)34.56 + (int)11.2;  // 丢失精度
y = (double)x + (double)10 + 1;  // 提高精度
Console.WriteLine("x=" + x);
Console.WriteLine("y=" + y);

4、各种数据类型的互相转换

数据类型

转换为其他类型

转换为字符串

转换为字符串

 byte

 Byte.Parse(str)

 Convert.ToString([byte] bt)

 b.toString()

 int

 int.Parse(str)

 Convert.ToString([int] i)

 i.toString()

 long

 long.Parse(str)

Convert.ToString([long] l)

 l.toString()

 float

 float.Parse(str)

Convert.ToString([float] f)

 f.toString()

 double

 double.Parse(str)

Convert.ToString([double] d)

 d.toString()

 char

 str.ToCharArray()

Convert.ToString([char] c)

 c.toString()

 bool

 Boolean.Parse(str)

Convert.ToString([boolean] b)

 bl.toString()

StringBuilder转化为string

    string str = "abcdefghijklmnopqrs";
    StringBuilder stb = new StringBuilder(str);

整型数组转化为字符串

    StringBuilder s = new StringBuilder();
    for(i=1;i<=n;i++) {
        s.Append(a[i].ToString());
    }
    string str = ""+s;           

字符串转化为整形数组

    string str="123456";
    int[] a = new int[str.Length];
    for(int i=0;i<str.Length;i++) {
        a[i]  = str[i]-'0';
    }

字符串转化为字符数组

    string str="123456";
    char[] c = str.ToCharArray() ;
    Console.WriteLine(c);

字符数组转化为字符串

char[] c = {'a','s','d','4','5',};
    string str = new string(c);
    Console.WriteLine(str);

字符数组转化为整型数组

char[] c = { '1', '2', '3', '4', '5', };
    int[] a = new int[c.Length];
    for (int i = 0; i < 5; i++) {
        a[i] = c[i] - '0';
        Console.WriteLine(a[i]);
    }

整型数组转化为字符数组

int[] a = {1,2,3,4,5};
    char[] c = new char[a.Length];
    for (int i = 0; i < 5; i++) {
        c[i] = (char) (a[i]+'0');
        Console.WriteLine(c[i]);
    }

整型数转化为字符串

int i=11;
string str = i.ToString();
string s = Convert.ToString(i);
s = "" + i;

字符串转化为整型数

int i = int.Parse(str);

5、使用 Convert 类进行转换

Convert 类提供了很多静态方法用于将不同类型之间进行转换。它比直接强制转换更安全,因为它会处理异常(如无效转换)。

string str = "123";
int i = Convert.ToInt32(str);  // 将字符串转换为 int
Console.WriteLine(i);  // 输出: 123

6、自定义类型转换

可以在自定义类中实现 implicitexplicit 操作符,以便在类的实例之间进行隐式或显式转换。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            // 使用隐式转换
           Fahrenheit fahrenheit = new Fahrenheit(100);
           // 自动将 Fahrenheit 转换为 Celsius
           Celsius celsius = fahrenheit;  
           // 输出: 37.77777777777778
           Console.WriteLine(celsius.Temperature);  
            Console.ReadKey();
        }
    }
}

public class Fahrenheit
{
    public double Temperature { get; set; }

    public Fahrenheit(double temperature)
    {
        Temperature = temperature;
    }

    // 隐式转换
    public static implicit operator Celsius(Fahrenheit fahrenheit)
    {
        return new Celsius((fahrenheit.Temperature - 32) * 5 / 9);
    }
}

public class Celsius
{
    public double Temperature { get; set; }

    public Celsius(double temperature)
    {
        Temperature = temperature;
    }
}

推荐文档