详解c# 类型转换
- 作者: 已认证58290779
- 来源: 51数据库
- 2021-08-27
类型转换从根本上说是类型铸造,或者说是把数据从一种类型转换为另一种类型。在 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
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
以上就是详解c# 类型转换的详细内容,更多关于c# 类型转换的资料请关注其它相关文章!
推荐阅读
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
热点文章
团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
0
使用 MSBuild.exe 在发布模式下构建 C# 解决方案
0
当我发布 Web 应用程序时,AfterPublish 脚本不运行
0
构建时 T4 转换的产品仅在下一个构建中使用
0
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
0
新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
0
如何将条件编译符号(DefineConstants)传递给 msbuild
0
MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
0
NuGet 包还原找不到包,没有源
0
使用 C# 6.0 功能运行 TFS 构建
0
