ushort(C# 参考)

ushort 关键字表示整数数据类型,该类型根据下表显示的大小和范围存储值。

类型 范围 大小 .NET Framework 类型
ushort 0 到 65,535 无符号 16 位整数 System.UInt16

文本

可如下例所示声明并初始化 ushort 类型的变量:


ushort myShort = 65535;

在以上声明中,整数 65535 从 int 隐式转换为 ushort。如果整数超出了 ushort 的范围,将产生编译错误。

调用重载方法时,必须使用强制转换。以下面使用 ushortint 参数的重载方法为例:

public static void SampleMethod(int i) {}
public static void SampleMethod(ushort s) {}

使用 ushort 强制转换可保证调用正确的类型,例如:

// Calls the method with the int parameter:
SampleMethod(5);
// Calls the method with the ushort parameter:
SampleMethod((ushort)5);

转换

存在从 ushortintuintlongulongfloatdoubledecimal 的预定义隐式转换。

存在从 bytecharushort 的预定义隐式转换。其他情况下必须使用显式转换。例如,请看以下两个 ushort 变量 x 和 y:


ushort x = 5, y = 12;

以下赋值语句将产生一个编译错误,原因是赋值运算符右侧的算术表达式在默认情况下的计算结果为 int


ushort z = x + y;   // Error: conversion from int to ushort

若要解决此问题,请使用强制转换:


ushort z = (ushort)(x + y);   // OK: explicit conversion

但是,在目标变量具有相同或更大的存储大小时,使用下列语句是可能的:

int m = x + y;
long n = x + y;

还请注意,不存在从浮点型到 ushort 类型的隐式转换。例如,除非使用显式强制转换,否则以下语句将生成一个编译器错误:

// Error -- no implicit conversion from double:
ushort x = 3.0; 
// OK -- explicit conversion:
ushort y = (ushort)3.0;

有关兼用浮点型和整型的算术表达式的信息,请参见 floatdouble

有关隐式数值转换规则的更多信息,请参见隐式数值转换表(C# 参考)

C# 语言规范

有关详细信息,请参阅 C# 语言规范。该语言规范是 C# 语法和用法的权威资料。

请参阅

UInt16

C# 参考

C# 编程指南

C# 关键字

整型表(C# 参考)

内置类型表(C# 参考)

隐式数值转换表(C# 参考)

显式数值转换表(C# 参考)