类型转换可将一种类型的数据转换为另一种类型。它也被称为类型铸造。在 c# 中,类型转换有两种形式:
以下示例显示了显式类型转换用法:
using system;
namespace typeconversionapplication
{
class explicitconversion
{
static void main(string[] args)
{
double d = 9999.98;
int i;
// cast double to int.
i = (int)d;
console.writeline(i);
console.readkey();
}
}
}
当编译和执行上述代码时,会产生以下结果:
9999
c# 提供以下内置类型转换方法:
| 序号 | 方法 | 描述 |
|---|---|---|
| 1 | toboolean() |
如果可能,将类型转换为布尔值。 |
| 2 | tobyte() |
将类型转换为字节类型值。 |
| 3 | tochar() |
如果可能,将类型转换为单个unicode字符。 |
| 4 | todatetime() |
将类型(整数或字符串类型)转换为日期时间结构。 |
| 5 | todecimal() |
将浮点或整数类型转换为十进制类型。 |
| 6 | todouble() |
将类型转换为double类型。 |
| 7 | toint16() |
将类型转换为16位整数。 |
| 8 | toint32() |
将类型转换为32位整数。 |
| 9 | toint64() |
将类型转换为64位整数。 |
| 10 | tosbyte() |
将类型转换为有符号字节类型。 |
| 11 | tosingle() |
将类型转换为小浮点数。 |
| 12 | tostring() |
将类型转换为字符串。 |
| 13 | totype() |
将类型转换为指定的类型。 |
| 14 | touint16() |
将类型转换为unsigned int类型。 |
| 15 | touint32() |
将类型转换为unsigned double类型。 |
| 16 | touint64() |
将类型转换为无符号大整数。 |
以下示例将各种值类型转换为字符串类型:
using system;
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