扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
Java 和 C# 遵守相似的数据类型自动转换和强制转换规则。
同 Java 一样,C# 既支持隐式类型转换又支持显式类型转换。在扩大转换的情况下,转换是隐式的。例如,下面从 int 到 long 的转换是隐式的,如同 Java 中的一样:
int intVariable = 5; long l = intVariable;
下面是 .NET 数据类型之间的隐式转换列表:
|
源类型 |
目标类型 |
|---|---|
|
byte |
short, ushort, int, uint, long, ulong, float, double 或 decimal |
|
sbyte |
short, int, long, float, double, ? decimal |
|
int |
long, float, double, 或 decimal |
|
uint |
long, ulong, float, double, 或 decimal |
|
short |
int, long, float, double, 或 decimal |
|
ushort |
int, uint, long, ulong, float, double, 或 decimal |
|
long |
float, double, 或 decimal |
|
ulong |
float, double, 或 decimal |
|
float |
double |
|
char |
ushort, int, uint, long, ulong, float, double, 或 decimal |
可以使用与 Java 一样的语法对希望显式转换的表达式进行强制转换:
long longVariable = 5483; int intVariable = (int)longVariable;
|
源类型 |
目标类型 |
|---|---|
|
byte |
sbyte 或 char |
|
sbyte |
byte, ushort, uint, ulong, 或 char |
|
int |
sbyte, byte, short, ushort, uint, ulong, 或 char |
|
uint |
sbyte, byte, short, ushort, int, 或 char |
|
short |
sbyte, byte, ushort, uint, ulong, 或 char |
|
ushort |
sbyte, byte, short, 或 char |
|
long |
sbyte, byte, short, ushort, int, uint, ulong, 或 char |
|
ulong |
sbyte, byte, short, ushort, int, uint, long, 或 char |
|
float |
sbyte, byte, short, ushort, int, uint, long, ulong, char, 或 decimal |
|
double |
sbyte, byte, short, ushort, int, uint, long, ulong, char, float, 或 decimal |
|
char |
sbyte, byte, 或 short |
|
decimal |
sbyte, byte, short, ushort, int, uint, long, ulong, char, float, 或 double |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。