C# 常用数据类型转换(一)

1. 数值类型之间的相互转换
数值类型包括 byte, short, int, long, fload, double 等,根据这个排列顺序,各种类型的值依次可以向后自动进行转换。
如下例:

namespace ConsoleApplicationTest
{
    class Program
    {
        static void Main(string[] args)
        {
            byte   a = 1; 
            short  b = a; 
            int    c = b;
            long   d = c; 
            float  e = d; 
            double f = e;

            Console.WriteLine("byte a = " + a.ToString());
            Console.WriteLine("short b = " + b.ToString());
            Console.WriteLine("int c = " + c.ToString());
            Console.WriteLine("long d = " + d.ToString());
            Console.WriteLine("float e = " + e.ToString());
            Console.WriteLine("double f = " + f.ToString());
            Console.ReadLine();
        }
    }
}

译顺利通过,运行结果是各变量的值均为 1;当然,它们的类型分别还是 System.Byte 型……System.Double 型。现在我们来试试,如果把赋值的顺序反过来会怎么样呢?

        static void Main(string[] args)
        {
            int g = 1;
            short h = g; // 编译错误

            // 这是使用强制类型转换
            short g1 = 1;
            byte h1 = (byte)g1; // 将 short 型的 g 的值强制转换成 short 型后再赋给变量 h
            Console.WriteLine("byte h1 = " + h1.ToString()); // 输出 byte h1 = 1

            Console.ReadLine();
        }

但是,如果我们使用强制转换,就不得不再考虑一个问题:short 型的范围是 -32768 ~ 23767,而 byte 型的范围是 0 ~ 255,那么,如果变量 g 的大小超过了 byte 型的范围又会出现什么样的情况呢?

        static void Main(string[] args)
        {
            short a = 300;
            byte b = (byte)a;

            Console.WriteLine("byte b = " + b.ToString()); // 输出 byte b = 44

            Console.ReadLine();
        }

在进行转换的时候,应当注意被转换的数据不能超出目标类型的范围。这不仅体现在多字节数据类型(相对,如上例的 short) 转换为少字节类型(相对,如上例的 byte) 时,也体现在字节数相同的有符号类型和无符号类型之间,如将 byte 的 129 转换为 sbyte 就会溢出。

decimal类型
在C#里是表示 128 位数据类型。double相比,decimal 类型具有更高的精度和更小的范围,它适合于财务和货币计算。
decimal:
有效位:±1.0 × 10(-28次方) 到 ±7.9 × 10(28次方) 精度:28 到 29 位 double: 有效位:±5.0 × 10(-324次方) 到 ±1.7 × 10(308次方) 精度:15 到 16 位

2. 字符的 ASCII 码和 Unicode 码
很多时候我们需要得到一个英文字符的 ASCII 码,或者一个汉字字符的 Unicode 码,或者从相关的编码查询它是哪一个字符的编码。C# 中字符的范围扩大了,不仅包含了单字节字符,也可以包含双字节字符,如中文字符等。而在字符和编码之间的转换,则仍延用了 C 语言的做法——强制转换。
如下例:

        static void Main(string[] args)
        {
            char ch = 'a'; short ii = 65;
            Console.WriteLine("The ASCII code of " + ch + " is: " + (short)ch );
            Console.WriteLine("ASCII is " + ii.ToString() + ", the char is: " + (char)ii );

            char cn = '中'; short uc = 22478;
            Console.WriteLine("The Unicode of " + cn + " is: " + (short)cn);
            Console.WriteLine("Unicode is " + uc.ToString() + ", the char is: " + (char)uc);

            Console.ReadLine();
        }

运行结果:
The ASCII code of ‘a’ is: 97
ASCII is 65, the char is: A
The Unicode of ‘中’ is: 20013
Unicode is 22478, the char is: 城

从这个例子中,我们便能非常清楚的了解——通过强制转换,可以得以字符的编码,或者得到编码表示的字符

3. 数值字符串和数值之间的转换
将数值转换成字符串非常简单,因为每一个类都有一个 void ToString() 方法。所有数值型的 void ToString() 方法都能将数据转换为数值字符串。如 123.ToSting() 就将得到字符串 “123”。

将数值型字符串转换成数值 可以使用short, int, float 等数值类型的static Parse() 函数。这个函数就是用来将字符串转换为相应数值的。我们以一个 float 类型的转换为例: float f = float.Parse(“543.21”); 其结果 f 的值为 543.21F。也可以使用Convert.ToInt16(string), Convert.ToInt32(string), Convert.ToSingle(string)等函数。
例子:

        static void Main(string[] args)
        {
            // 取一个double类型精确一位小数后的整数部分、小数部分和每个位的数字
            double val = 123.74;
            val = System.Math.Round(val, 1);

            string[] strs = val.ToString().Split('.');

            int gInteger = Convert.ToInt32(strs[0]);
            int gunitPlace = gInteger / 1 % 10;
            int gtenPlace = gInteger / 10 % 10;
            int ghundredPlace = gInteger / 100 % 10;
            int gthousandPlace = gInteger / 1000 % 10;

            Console.WriteLine("整数部分值为:" + gInteger.ToString());
            Console.WriteLine("个位数值为:" + gunitPlace.ToString());
            Console.WriteLine("十位数值为:" + gtenPlace.ToString());
            Console.WriteLine("百位数值为:" + ghundredPlace.ToString());
            Console.WriteLine("千位数值为:" + gthousandPlace.ToString());

            int gdecimals = Convert.ToInt32(strs[1]);
            Console.WriteLine("小数部分值为:" + gdecimals.ToString());

            Console.ReadLine();
        }

输出结果为:
整数部分值为:123
个位数值为:3
十位数值为:2
百位数值为:1
千位数值为:0
小数部分值为:7

4. 字符串和字符数组之间的转换
字符串转换为字符数组:字符串类 System.String 提供了一个 void ToCharArray() 方法,该方法可以实现字符串到字符数组的转换。
例子:

        static void Main(string[] args)
        {
            string str = "mytest";
            char[] chars = str.ToCharArray();

            Console.WriteLine("Length of str is " + str.Length);
            Console.WriteLine("Length of char array is " + chars.Length);
            Console.WriteLine("char[2] = " + chars[2]);

            Console.ReadLine();
        }

输出:
Length of “mytest” is 6
Length of char array is 6
char[2] = t

字符数组转换为字符串: System.String 类有两个构造函数是通过字符数组来构造的,即 String(char[]) 和 String[char[], int, int)。后者之所以多两个参数,是因为可以指定用字符数组中的哪一部分来构造字符串。而前者则是用字符数组的全部元素来构造字符串。
例子:

        static void Main(string[] args)
        {
            char[] tcs = {'t', 'e', 's', 't', ' ', 'm', 'e'};
            string tstr = new String(tcs);

            Console.WriteLine(tstr);
            Console.ReadLine();
        }

输出:
test me

5. 字符串和字节数组之间的转换
字符串转换成字节数组: System.Text.Encoding。该类提供了 bye[] GetBytes(string) 方法将字符串转换成字节数组。
在字符串转换到字节数组的过程中,Encoding.Default 会将每个单字节字符,如半角英文,转换成 1 个字节,而把每个双字节字符,如汉字,转换成 2 个字节。而 Encoding.Unicode 则会将它们都转换成两个字节。
例子:

        static void Main(string[] args)
        {
            string s = "C#语言";
            byte[] b1 = System.Text.Encoding.Default.GetBytes(s);
            byte[] b2 = System.Text.Encoding.Unicode.GetBytes(s);
            string t1 = "", t2 = "";
            foreach (byte b in b1)
            {
                t1 += b.ToString("") + " ";
            }
            foreach (byte b in b2)
            {
                t2 += b.ToString("") + " ";
            }

            Console.WriteLine("b1.Length = " + b1.Length);
            Console.WriteLine(t1);
            Console.WriteLine("b2.Length = " + b2.Length);
            Console.WriteLine(t2);

            Console.ReadLine();
        }

输出:
b1.Length = 6
67 35 211 239 209 212
b2.Length = 8
67 0 35 0 237 139 0 138

字节数组转换成字符串: 还提供了 string GetString(byte[]) 方法将字节数组转换成字符串。
例子:

        static void Main(string[] args)
        {
            byte[] bs = { 97, 98, 99, 100, 101, 102 };
            string ss = System.Text.Encoding.ASCII.GetString(bs);
            Console.WriteLine("The string is: " + ss );

            Console.ReadLine();
        }

输出:
The string is: abcdef

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值