C# 类型转换
c# 类型转换
类型转换从根本上说是类型铸造,或者说是把数据从一种类型转换为另一种类型。在 c# 中,类型铸造有两种形式:
- 隐式类型转换 - 这些转换是 c# 默认的以安全方式进行的转换, 不会导致数据丢失。例如,从小的整数类型转换为大的整数类型,从派生类转换为基类。
- 显式类型转换 - 显式类型转换,即强制类型转换。显式转换需要强制转换运算符,而且强制转换会造成数据丢失。
下面的范例显示了一个显式的类型转换:
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
1. c# 类型转换方法
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


