C# 类型转换方法
类型转换从根本上说是把数据从一种类型转换为另一种类型。在 C# 中,类型转换有两种形式:
- 隐式类型转换 - 这些转换是 C# 默认的以安全方式进行的转换, 不会导致数据丢失。例如,从小的整数类型转换为大的整数类型,从派生类转换为基类。
- 显式类型转换 - 显式类型转换,即强制类型转换。显式转换需要强制转换运算符,而且强制转换会造成数据丢失。转换类型的范围大小和从属关系和隐式转换相反。显式转换可能会导致数据出错,或者转换失败,甚至无法编译成功。
下面的实例显示了一个隐式的类型转换:
namespace TypeConvertion
{ class Base
{
}
class Derive : Base //类Derive是类Base的子类
{
}
class Program
{
static void Main(string[] args)
{
int inum = 100;
long lnum = inum; // 进行了隐式转换,将 int 型(数据范围小)数据转换为了 long 型(数据范围大)的数据
Base b = new Derive(); // 这里也是隐式转换,将一个新建的 Derive 实例转换为了其基类 Base 类型的实例b
}
}
}
下面的实例显示了一个显式的类型转换:
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
double d = 5673.74;
int i;
// 强制转换 double 为 int
i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}
当上面的代码被编译和执行时,它会产生下列结果:
5673
显示转换的例子2:
double dnum = 100.1;
int ifromd = (int)dnum; //double类型显式转换转为int类型
Base b = new Derive();
Derive d = b as Derive; //使用as进行显式转换
Console.WriteLine(d is Base);
Console.WriteLine(d is Derive);
运行结果:
FALSE
FALSE
C# 类型转换方法
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();
}
}
}
当上面的代码被编译和执行时,它会产生下列结果:
75
53.005
2345.7652
True
2、C# 提供了Convert和Parse的类型转换方法:
using System;
namespace TypeConversion
{
class ConversionDemo
{
static void Main(string[] args)
{
string locstr = 123.ToString();
//如果要将"locstr"转成整型数
//方法一: 用 Convert
int i = Convert.ToInt16(locstr);
Console.WriteLine(i);
//方法二: 用 Parse
int ii = int.Parse(locstr);
Console.WriteLine(ii);
/*int.TryParse(string s,out int i);
该方式也是将数字内容的字符串转换为int类型,
但是该方式比int.Parse(string s) 好一些,它不会出现异常,最后一个参数result是输出值,
如果转换成功则输出相应的值,转换失败则输出0。*/
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