C#点滴 - 类型转换
2010-03-26 15:50
141 查看
1. 宽化转换() – Widening Conversions
从数据范围较窄的类型转换到数据范围较宽的类型,一般情况下不会带来数据的损失。
但是在从整形到浮点类型转换的工程中,可能会造成数据精度损失。
2. 窄化转换 – Narrowing Conversions
基本上.NET是不支持窄化转换的,所有的隐式的窄化都会造成编译错误。如果真的需要进行窄化转换,必须要进行强制转化或者使用System.Convert类中的方法。
默认情况下,即使溢出发生,强制窄化不会跑出异常。为了捕捉在窄化转换发生的错误,经常使用checked关键字,如:
checked {
int i = 10000;
short j = (short)i;
}
而如果使用了System.Convert进行强制窄化转换,在溢出时一定会抛出异常。下面是一些进行窄化转换是溢出抛出异常的情况:
从数据范围较窄的类型转换到数据范围较宽的类型,一般情况下不会带来数据的损失。
类型 | 不损失数据的可以转化目标类型 |
Byte | UInt16, Int16, UInt32, Int32, UInt64, Int64, Single, Double, Decimal |
SByte | Int16, Int32, Int64, Single, Double, Decimal |
Int16 | Int32, Int64, Single, Double, Decimal |
UInt16 | UInt32, Int32, UInt64, Int64, Single, Double, Decimal |
Char | UInt16, UInt32, Int32, UInt64, Int64, Single, Double, Decimal |
Int32 | Int64, Double, Decimal |
UInt32 | Int64, Double, Decimal |
Int64 | Decimal |
UInt64 | Decimal |
Single | Double |
类型 | 可以转化目标类型 |
Int32 | Single |
UInt32 | Single |
Int64 | Single, Double |
UInt64 | Single, Double |
Decimal | Single, Double |
基本上.NET是不支持窄化转换的,所有的隐式的窄化都会造成编译错误。如果真的需要进行窄化转换,必须要进行强制转化或者使用System.Convert类中的方法。
默认情况下,即使溢出发生,强制窄化不会跑出异常。为了捕捉在窄化转换发生的错误,经常使用checked关键字,如:
checked {
int i = 10000;
short j = (short)i;
}
而如果使用了System.Convert进行强制窄化转换,在溢出时一定会抛出异常。下面是一些进行窄化转换是溢出抛出异常的情况:
类型 | 转化的目标类型 |
Byte | Sbyte |
SByte | Byte, UInt16, UInt32, UInt64 |
Int16 | Byte, SByte, UInt16 |
UInt16 | Byte, SByte, Int16 |
Char | Byte, SByte, Int16, UInt16, UInt32 |
Int32 | Byte, SByte, Int16, UInt16, Int32 |
UInt32 | Byte, SByte, Int16, UInt16, Int32, UInt32, UInt64 |
Int64 | Byte, SByte, Int16, UInt16, Int32, UInt32, Int64 |
UInt64 | Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64 |
Single | Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64 |
Double | Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64 |
相关文章推荐
- C#调用C++的DLL搜集整理的所有数据类型转换方式
- .net学习之.net和C#关系、运行过程、数据类型、类型转换、值类型和引用类型、数组以及方法参数等
- C#类型转换1
- 一个数字转中文大写货币数字的类.完美兼容于C#所有值类型转换和操作,beta版.希望大家多多纠正.
- 关于C#数据类型之间转换的讨论
- C# 数据类型转换
- C# 把字符串类型日期转换为日期类型
- C#中如何把byte[]数组转换成其他类型
- c#数据类型转换
- 追着嘟嘟学c#系列入门第五篇-----c#的类型转换【蓝鸥出品】
- 用C#调用ffmpeg实现媒体类型转换(1)
- C/C++ 和 C#之间的类型转换
- C#调用C++的DLL搜集整理的所有数据类型转换方式
- C# 调用C++ DLL 的类型转换(转载版)
- 【c#】类型转换
- C# 不同类型数组之间的转换
- C# .Net中的类型转换(转载)
- C# 关于类型转换 面试题
- C#学习笔记(基础知识回顾)之值类型与引用类型转换(装箱和拆箱)
- C#.NET中的类型转换