类型转换从根本上说是把数据从一种类型转换为另一种类型。在 C# 中,类型转换有两种形式:
- 隐式类型转换 - 这些转换是 C# 默认的以安全方式进行的转换, 不会导致数据丢失。例如,从小的整数类型转换为大的整数类型,从派生类转换为基类。
- 显式类型转换 - 显式类型转换,即强制类型转换。显式转换需要强制转换运算符,而且强制转换会造成数据丢失。转换类型的范围大小和从属关系和隐式转换相反。显式转换可能会导致数据出错,或者转换失败,甚至无法编译成功。
下面的实例显示了一个隐式的类型转换:
- namespace TypeConvertion
- { class Base
- {
-
- }
- class Derive : Base
- {
-
- }
- class Program
- {
- static void Main(string[] args)
- {
- int inum = 100;
- long lnum = inum;
- Base b = new Derive();
- }
- }
- }
下面的实例显示了一个显式的类型转换:
- namespace TypeConversionApplication
- {
- class ExplicitConversion
- {
- static void Main(string[] args)
- {
- double d = 5673.74;
- int i;
-
-
- i = (int)d;
- Console.WriteLine(i);
- Console.ReadKey();
-
- }
- }
- }
当上面的代码被编译和执行时,它会产生下列结果:
显示转换的例子2:
- double dnum = 100.1;
- int ifromd = (int)dnum;
-
- Base b = new Derive();
- Derive d = b as Derive;
- Console.WriteLine(d is Base);
- Console.WriteLine(d is Derive);
运行结果:
1、C# 提供了下列内置的类型转换方法:
序号 | 方法 & 描述 |
---|
1 | ToBoolean 如果可能的话,把类型转换为布尔型。 |
2 | ToByte 把类型转换为字节类型。 |
3 | ToChar 如果可能的话,把类型转换为单个 Unicode 字符类型。 |
4 | ToDateTime 把类型(整数或字符串类型)转换为 日期-时间 结构。 |
5 | ToDecimal 把浮点型或整数类型转换为十进制类型。 |
6 | ToDouble 把类型转换为双精度浮点型。 |
7 | ToInt16 把类型转换为 16 位整数类型。 |
8 | ToInt32 把类型转换为 32 位整数类型。 |
9 | ToInt64 把类型转换为 64 位整数类型。 |
10 | ToSbyte 把类型转换为有符号字节类型。 |
11 | ToSingle 把类型转换为小浮点数类型。 |
12 | ToString 把类型转换为字符串类型。 |
13 | ToType 把类型转换为指定类型。 |
14 | ToUInt16 把类型转换为 16 位无符号整数类型。 |
15 | ToUInt32 把类型转换为 32 位无符号整数类型。 |
16 | ToUInt64 把类型转换为 64 位无符号整数类型。 |
下面的实例把不同值的类型转换为字符串类型:
- namespace TypeConversionApplication
- {
- class StringConversion
- {
- static void Main(string[] args)
- {
- int i = 75;
- float f = 53.005f;
- double d = 2345.7652;
- bool b = true;
-
- Console.WriteLine(i.ToString());
- Console.WriteLine(f.ToString());
- Console.WriteLine(d.ToString());
- Console.WriteLine(b.ToString());
- Console.ReadKey();
-
- }
- }
- }
当上面的代码被编译和执行时,它会产生下列结果:
2、C# 提供了Convert和Parse的类型转换方法:
- using System;
-
- namespace TypeConversion
- {
- class ConversionDemo
- {
- static void Main(string[] args)
- {
- string locstr = 123.ToString();
-
-
- int i = Convert.ToInt16(locstr);
- Console.WriteLine(i);
-
-
- int ii = int.Parse(locstr);
- Console.WriteLine(ii);
-
-
-
-
-
-
- string s1 = "abcd";
- string s2 = "1234";
- int a, b;
-
- bool bo1 = int.TryParse(s1, out a);
- Console.WriteLine(s1 + " " + bo1 + " " + a);
-
- bool bo2 = int.TryParse(s2, out b);
- Console.WriteLine(s2 + " " + bo2 + " " + b);
- }
- }
- }
运行结果:
- 123
- 123
- abcd False 0
- 1234 True 1234