System.Convert.ToUInt16 方法 (Object, IFormatProvider)

方法描述

使用指定的区域性特定格式信息,将指定对象的值转换为 16 位无符号整数。

语法定义(C# System.Convert.ToUInt16 方法 (Object, IFormatProvider) 的用法)

[CLSCompliantAttribute(false)]
public static ushort ToUInt16(
	Object value,
	IFormatProvider provider
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
value System-Object 用于实现 IConvertible 接口的对象。
provider System-IFormatProvider 一个提供区域性特定的格式设置信息的对象。
返回值 System.UInt16 与 value 等效的 16 位无符号整数,如果 value 为 null,则为零。

提示和注释

返回值是调用 value 的基础类型的 IConvertible.ToUInt16 方法的结果。

provider 使用户得以指定关于 value 内容的区域性特定转换信息。 例如,如果 value 是表示数字的 String,则 provider 可以提供有关用于表示该数字的表示法的区域性特定信息。

基类型忽略 provider;但是如果 value 是实现 IConvertible 接口的用户定义的类型,则可能会使用该参数。

System.Convert.ToUInt16 方法 (Object, IFormatProvider)例子

下面的示例演示了对 ToUInt16(Object, IFormatProvider) 方法(将 HexString 对象作为参数传递)的调用进而调用 HexString 类的 IConvertible.ToUInt16 实现。

public class Example
{
   public static void Main()
   {
      ushort positiveValue = 32000;
      short negativeValue = -1;

      HexString positiveString = new HexString();
      positiveString.Sign = (SignBit) Math.Sign(positiveValue);
      positiveString.Value = positiveValue.ToString("X2");

      HexString negativeString = new HexString();
      negativeString.Sign = (SignBit) Math.Sign(negativeValue);
      negativeString.Value = negativeValue.ToString("X2");

      try {
         Console.WriteLine("0x{0} converts to {1}.", positiveString.Value, Convert.ToUInt16(positiveString));
      }
      catch (OverflowException) {
         Console.WriteLine("{0} is outside the range of the UInt16 type.", 
                           Int16.Parse(negativeString.Value, NumberStyles.HexNumber));
      }

      try {
         Console.WriteLine("0x{0} converts to {1}.", negativeString.Value, Convert.ToUInt16(negativeString));
      }
      catch (OverflowException) {
         Console.WriteLine("{0} is outside the range of the UInt16 type.", 
                           Int16.Parse(negativeString.Value, NumberStyles.HexNumber));
      }   
   }
}
// The example displays the following output:
//       0x7D00 converts to 32000.
//       -1 is outside the range of the UInt16 type.

异常

异常 异常描述
FormatException value 的格式不正确。
InvalidCastException
  • value 未实现 IConvertible 接口。
  • 不支持该转换。
OverflowException value 表示小于 UInt16.MinValue 或大于 UInt16.MaxValue 的数字。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。