数值转换(Convert/Int32)

<script type=text/javascript> // </script> <script src="/WebResource.axd?d=y48MEe_dRk_v_rnD4dSyAA2&t=633527533112930887" type=text/javascript></script> <script src="http://i2.technet.microsoft.com/Platform/cjs/Silverlight-bn2008.3.js" type=text/javascript></script> <script type=text/javascript> //<//scr"+"ipt>");} /*]]>*/ var detectedLocale = 'zh-cn'; var wtsp="_technet_sysinternals_"; var gTrackEvents = 0; //]]> </script> <script src="http://i2.technet.microsoft.com/platform/cjs/extract/compositejscript1.js" type=text/javascript></script> <script src="http://i2.technet.microsoft.com/platform/cjs/extract/Microsoft.Mtps.Web.UI/3.810.2008.3/0.0.0.0/Microsoft.Mtps.Web.UI.CollapsiblePanel.CollapsiblePanelBehavior.js" type=text/javascript></script> <script type=text/javascript> // </script>
中国 - 简体中文  Dropdown Arrow
欢迎您 登录
Convert 类
将一个基本数据类型转换为另一个基本数据类型。

命名空间: System
程序集: mscorlib(在 mscorlib.dll 中)

Visual Basic(声明)
Public NotInheritable Class Convert
Visual Basic (用法)
C#
public static class Convert
C++
public ref class Convert abstract sealed
J#
public final class Convert
JScript
public final class Convert
XAML
不适用。

该类返回值与指定类型的值等效的类型。受支持的基类型是 BooleanCharSByteByteInt16Int32Int64UInt16UInt32UInt64SingleDoubleDecimalDateTimeString

存在将每个基类型转换为每个其他基类型的转换方法。不过,所执行的实际转换操作分为三类:

  • 从某类型到它本身的转换只返回该类型。不实际执行任何转换。

  • 无法产生有意义的结果的转换引发 InvalidCastException。不实际执行任何转换。下列转换会引发异常:从 Char 转换为 BooleanSingleDoubleDecimalDateTime,以及从这些类型转换为 Char。下列转换会引发异常:从 DateTime 转换为除 String 之外的任何类型,以及从任何类型(String 除外)转换为 DateTime

  • 任何基类型(上面描述的基类型除外)都可以与任何其他基类型进行相互转换。

如果数字类型转换导致精度丢失(即某些最低有效位丢失),不引发异常。但是,如果结果超出了特定转换方法的返回值类型所能表示的范围,则将引发异常。

例如,当将 Double 转换为 Single 时,可能会发生精度丢失,但并不引发异常。但是,如果 Double 的值太大,无法由 Single 表示,则将引发溢出异常。

有一组方法可支持字节数组与 String 或由以 64 为基的数字字符组成的 Unicode 字符数组之间的转换。表示为以 64 为基的数字的数据可以很容易地通过只能传输 7 位字符的数据信道进行传送。

该类中的一些方法带一个实现 IFormatProvider 接口的参数对象。该参数可以提供区域性特定的格式设置信息以帮助转换过程。基值类型忽略该参数,但任何实现 IConvertible 的用户定义类型可以考虑使用它。

有关基值类型的更多信息,请参见“请参见”一节中列出的相应主题。

下面的代码示例演示 Convert 类中的一些转换方法,包括 ToInt32ToBooleanToString

Visual Basic
Dim dNumber As Double
dNumber = 23.15

Try
   ' Returns 23
   Dim iNumber As Integer
   iNumber = System.Convert.ToInt32(dNumber)
Catch exp As System.OverflowException
   System.Console.WriteLine("Overflow in double to int conversion.")
End Try

' Returns True
Dim bNumber As Boolean
bNumber = System.Convert.ToBoolean(dNumber)

' Returns "23.15"
Dim strNumber As String
strNumber = System.Convert.ToString(dNumber)

Try
   ' Returns '2'
   Dim chrNumber As Char
   chrNumber = System.Convert.ToChar(strNumber.Chars(1))
Catch exp As System.ArgumentNullException
   System.Console.WriteLine("String is null.")
Catch exp As System.FormatException
   System.Console.WriteLine("String length is greater than 1.")
End Try

' System.Console.ReadLine() returns a string and it
' must be converted.
Dim newInteger As Integer
newInteger = 0
Try
   System.Console.WriteLine("Enter an integer:")
   newInteger = System.Convert.ToInt32(System.Console.ReadLine())
Catch exp As System.ArgumentNullException
   System.Console.WriteLine("String is null.")
Catch exp As System.FormatException
   System.Console.WriteLine("String does not consist of an " + _
       "optional sign followed by a series of digits.")
Catch exp As System.OverflowException
   System.Console.WriteLine("Overflow in string to int conversion.")
End Try

System.Console.WriteLine("Your integer as a double is {0}", _
                         System.Convert.ToDouble(newInteger))
double dNumber = 23.15;

try {
    // Returns 23
    int    iNumber = System.Convert.ToInt32(dNumber);
}
catch (System.OverflowException) {
    System.Console.WriteLine(
                "Overflow in double to int conversion.");
}
// Returns True
bool   bNumber = System.Convert.ToBoolean(dNumber);

// Returns "23.15"
string strNumber = System.Convert.ToString(dNumber);

try {
    // Returns '2'
    char chrNumber = System.Convert.ToChar(strNumber[0]);
} 
catch (System.ArgumentNullException) {
    System.Console.WriteLine("String is null");
}
catch (System.FormatException) {
    System.Console.WriteLine("String length is greater than 1.");
}

// System.Console.ReadLine() returns a string and it
// must be converted.
int newInteger = 0;
try {
    System.Console.WriteLine("Enter an integer:");
    newInteger = System.Convert.ToInt32(
                        System.Console.ReadLine());
}
catch (System.ArgumentNullException) {
    System.Console.WriteLine("String is null.");
}
catch (System.FormatException) {
    System.Console.WriteLine("String does not consist of an " +
                    "optional sign followed by a series of digits.");
} 
catch (System.OverflowException) {
    System.Console.WriteLine(
    "Overflow in string to int conversion.");
}

System.Console.WriteLine("Your integer as a double is {0}",
                         System.Convert.ToDouble(newInteger));
Double dNumber = 23.15;

try
{
   // Returns 23
   Int32 iNumber = Convert::ToInt32( dNumber );
}
catch ( OverflowException^ ) 
{
   Console::WriteLine(
      "Overflow in Double to Int32 conversion" );
}
// Returns True
Boolean bNumber = Convert::ToBoolean( dNumber );

// Returns "23.15"
String^ strNumber = Convert::ToString( dNumber );

try
{
   // Returns '2'
   Char chrNumber = Convert::ToChar( strNumber->Substring( 0, 1 ) );
}
catch ( ArgumentNullException^ ) 
{
   Console::WriteLine(  "String is null" );
}
catch ( FormatException^ ) 
{
   Console::WriteLine(  "String length is greater than 1" );
}

// System::Console::ReadLine() returns a string and it
// must be converted.
Int32 newInteger = 0;
try
{
   Console::WriteLine(  "Enter an integer:" );
   newInteger = Convert::ToInt32( System::Console::ReadLine() );
}
catch ( ArgumentNullException^ ) 
{
   Console::WriteLine(  "String is null" );
}
catch ( FormatException^ ) 
{
   Console::WriteLine(  "String does not consist of an " +
      "optional sign followed by a series of digits" );
}
catch ( OverflowException^ ) 
{
   Console::WriteLine(  "Overflow in string to Int32 conversion" );
}

Console::WriteLine( "Your integer as a Double is {0}",
   Convert::ToDouble( newInteger ) );
double dNumber = 23.15;

try {        
    // Returns 23
    int iNumber = System.Convert.ToInt32(dNumber);
}
catch (System.OverflowException exp) {        
    System.Console.WriteLine("Overflow in double to int conversion.");
}

// Returns True
boolean bNumber = System.Convert.ToBoolean(dNumber);

// Returns "23.15"
String strNumber = System.Convert.ToString(dNumber);

try {        
    // Returns '2'
    char chrNumber = System.Convert.ToChar(strNumber.get_Chars(0));
}
catch (System.ArgumentNullException exp) {        
    System.Console.WriteLine("String is null");
}
catch (System.FormatException exp) {        
    System.Console.WriteLine("String length is greater than 1.");
}

// System.Console.ReadLine() returns a string and it
// must be converted.
int newInteger = 0;

try {        
    System.Console.WriteLine("Enter an integer:");
    newInteger = System.Convert.ToInt32(System.Console.ReadLine());
}
catch (System.ArgumentNullException exp) {        
    System.Console.WriteLine("String is null.");
}
catch (System.FormatException exp) {        
    System.Console.WriteLine(("String does not consist of an " 
        + "optional sign followed by a series of digits."));
}
catch (System.OverflowException exp) {        
    System.Console.WriteLine("Overflow in string to int conversion.");
}
System.Console.WriteLine("Your integer as a double is {0}", 
    System.Convert.ToString(System.Convert.ToDouble(newInteger)));

下面的代码示例演示 Convert 类中的若干转换方法。

Visual Basic
' Sample for the Convert class summary.
Imports System

Class Sample
   Public Shared Sub Main()
      Dim nl As String = Environment.NewLine
      Dim str As String = "{0}Return the Int64 equivalent of the following base types:{0}"
      Dim xBool As Boolean = False
      Dim xShort As Short = 1
      Dim xInt As Integer = 2
      Dim xLong As Long = 3
      Dim xSingle As Single = 4F
      Dim xDouble As Double = 5.0
      Dim xDecimal As Decimal = 6D
      Dim xString As String = "7"
      Dim xChar As Char = "8"c ' '8' = hexadecimal 38 = decimal 56
      Dim xByte As Byte = 9
      
      '  The following types are not CLS-compliant.
      ' Dim xUshort As System.UInt16 = 120
      ' Dim xUint As System.UInt32 = 121
      ' Dim xUlong As System.UInt64 = 122
      ' Dim xSbyte As System.SByte = 123
      
      '  The following type cannot be converted to an Int64.
      '  Dim xDateTime As System.DateTime = DateTime.Now

      Console.WriteLine(str, nl)
      Console.WriteLine("Boolean:  {0}", Convert.ToInt64(xBool))
      Console.WriteLine("Int16:    {0}", Convert.ToInt64(xShort))
      Console.WriteLine("Int32:    {0}", Convert.ToInt64(xInt))
      Console.WriteLine("Int64:    {0}", Convert.ToInt64(xLong))
      Console.WriteLine("Single:   {0}", Convert.ToInt64(xSingle))
      Console.WriteLine("Double:   {0}", Convert.ToInt64(xDouble))
      Console.WriteLine("Decimal:  {0}", Convert.ToInt64(xDecimal))
      Console.WriteLine("String:   {0}", Convert.ToInt64(xString))
      Console.WriteLine("Char:     {0}", Convert.ToInt64(xChar))
      Console.WriteLine("Byte:     {0}", Convert.ToInt64(xByte))
      Console.WriteLine("DateTime: There is no example of this conversion because")
      Console.WriteLine("          a DateTime cannot be converted to an Int64.")
      '
      Console.Write("{0}The following types are not supported: ", nl)
      Console.WriteLine("UInt16, UInt32, UInt64, and SByte")
   End Sub 'Main
End Class 'Sample
'
'This example produces the following results:
'
'Return the Int64 equivalent of the following base types:
'
'Boolean:  0
'Int16:    1
'Int32:    2
'Int64:    3
'Single:   4
'Double:   5
'Decimal:  6
'String:   7
'Char:     56
'Byte:     9
'DateTime: There is no example of this conversion because
'          a DateTime cannot be converted to an Int64.
'
'The following types are not supported: UInt16, UInt32, UInt64, and SByte
'
// Sample for the Convert class summary.
using System;

class Sample 
{
    public static void Main() 
    {
    string nl = Environment.NewLine;
    string str = "{0}Return the Int64 equivalent of the following base types:{0}";
    bool    xBool = false;
    short   xShort = 1;
    int     xInt   = 2;
    long    xLong  = 3;
    float   xSingle = 4.0f;
    double  xDouble = 5.0;
    decimal xDecimal = 6.0m;
    string  xString = "7";
    char    xChar   = '8'; // '8' = hexadecimal 38 = decimal 56
    byte    xByte  =  9;

//  The following types are not CLS-compliant.
    ushort  xUshort = 120;   
    uint    xUint =   121;
    ulong   xUlong =  122;
    sbyte   xSbyte  = 123;

//  The following type cannot be converted to an Int64.
//  DateTime xDateTime = DateTime.Now;

    Console.WriteLine(str, nl);
    Console.WriteLine("Boolean:  {0}", Convert.ToInt64(xBool));
    Console.WriteLine("Int16:    {0}", Convert.ToInt64(xShort));
    Console.WriteLine("Int32:    {0}", Convert.ToInt64(xInt));
    Console.WriteLine("Int64:    {0}", Convert.ToInt64(xLong));
    Console.WriteLine("Single:   {0}", Convert.ToInt64(xSingle));
    Console.WriteLine("Double:   {0}", Convert.ToInt64(xDouble));
    Console.WriteLine("Decimal:  {0}", Convert.ToInt64(xDecimal));
    Console.WriteLine("String:   {0}", Convert.ToInt64(xString));
    Console.WriteLine("Char:     {0}", Convert.ToInt64(xChar));
    Console.WriteLine("Byte:     {0}", Convert.ToInt64(xByte));
    Console.WriteLine("DateTime: There is no example of this conversion because");
    Console.WriteLine("          a DateTime cannot be converted to an Int64.");
//
    Console.WriteLine("{0}The following types are not CLS-compliant.{0}", nl);
    Console.WriteLine("UInt16:   {0}", Convert.ToInt64(xUshort));
    Console.WriteLine("UInt32:   {0}", Convert.ToInt64(xUint));
    Console.WriteLine("UInt64:   {0}", Convert.ToInt64(xUlong));
    Console.WriteLine("SByte:    {0}", Convert.ToInt64(xSbyte));
    }
}
/*
This example produces the following results:

Return the Int64 equivalent of the following base types:

Boolean:  0
Int16:    1
Int32:    2
Int64:    3
Single:   4
Double:   5
Decimal:  6
String:   7
Char:     56
Byte:     9
DateTime: There is no example of this conversion because
          a DateTime cannot be converted to an Int64.

The following types are not CLS-compliant.

UInt16:   120
UInt32:   121
UInt64:   122
SByte:    123
*/
// Sample for the Convert class summary.
using namespace System;
int main()
{
   String^ nl = Environment::NewLine;
   String^ str = " {0}Return the Int64 equivalent of the following base types: {0}";
   bool xBool = false;
   short xShort = 1;
   int xInt = 2;
   long xLong = 3;
   float xSingle = 4.0f;
   double xDouble = 5.0;
   Decimal xDecimal = Decimal(6.0);
   String^ xString = "7";
   char xChar = '8'; // '8' = hexadecimal 38 = decimal 56

   Byte xByte = 9;
   
   //  The following types are not CLS-compliant.
   UInt16 xUshort = 120;
   UInt32 xUint = 121;
   UInt64 xUlong = 122;
   SByte xSbyte = 123;
   
   //  The following type cannot be converted to an Int64.
   //  DateTime xDateTime = DateTime::Now;
   Console::WriteLine( str, nl );
   Console::WriteLine( "Boolean: {0}", Convert::ToInt64( xBool ) );
   Console::WriteLine( "Int16: {0}", Convert::ToInt64( xShort ) );
   Console::WriteLine( "Int32: {0}", Convert::ToInt64( xInt ) );
   Console::WriteLine( "Int64: {0}", Convert::ToInt64( xLong ) );
   Console::WriteLine( "Single: {0}", Convert::ToInt64( xSingle ) );
   Console::WriteLine( "Double: {0}", Convert::ToInt64( xDouble ) );
   Console::WriteLine( "Decimal: {0}", Convert::ToInt64( xDecimal ) );
   Console::WriteLine( "String: {0}", Convert::ToInt64( xString ) );
   Console::WriteLine( "Char: {0}", Convert::ToInt64( xChar ) );
   Console::WriteLine( "Byte: {0}", Convert::ToInt64( xByte ) );
   Console::WriteLine( "DateTime: There is no example of this conversion because" );
   Console::WriteLine( "          a DateTime cannot be converted to an Int64." );
   
   //
   Console::WriteLine( " {0}The following types are not CLS-compliant. {0}", nl );
   Console::WriteLine( "UInt16: {0}", Convert::ToInt64( xUshort ) );
   Console::WriteLine( "UInt32: {0}", Convert::ToInt64( xUint ) );
   Console::WriteLine( "UInt64: {0}", Convert::ToInt64( xUlong ) );
   Console::WriteLine( "SByte: {0}", Convert::ToInt64( xSbyte ) );
}

/*
This example produces the following results:

Return the Int64 equivalent of the following base types:

Boolean:  0
Int16:    1
Int32:    2
Int64:    3
Single:   4
Double:   5
Decimal:  6
String:   7
Char:     56
Byte:     9
DateTime: There is no example of this conversion because
a DateTime cannot be converted to an Int64.

The following types are not CLS-compliant.

UInt16:   120
UInt32:   121
UInt64:   122
SByte:    123
*/
System.Object
   System.Convert
此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

Windows Vista、Microsoft Windows XP SP2 和 Windows Server 2003 SP1 支持 Microsoft .NET Framework 3.0。

.NET Framework

受以下版本支持:3.0、2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

XNA Framework

受以下版本支持:1.0

 

<script type=text/javascript> // </script> <script src="/WebResource.axd?d=y48MEe_dRk_v_rnD4dSyAA2&t=633527533112930887" type=text/javascript></script> <script src="http://i2.msdn.microsoft.com/Platform/cjs/Silverlight-bn2008.3.js" type=text/javascript></script> <script type=text/javascript> //<//scr"+"ipt>");} /*]]>*/ var detectedLocale = 'zh-cn'; var wtsp="_msdn_"; var gTrackEvents = 1; //]]> </script> <script src="http://i2.msdn.microsoft.com/platform/cjs/extract/compositejscript1.js" type=text/javascript></script> <script src="http://i2.msdn.microsoft.com/platform/cjs/extract/Microsoft.Mtps.Web.UI/3.810.2008.3/0.0.0.0/Microsoft.Mtps.Web.UI.CollapsiblePanel.CollapsiblePanelBehavior.js" type=text/javascript></script> <script type=text/javascript> // </script>
中国 - 简体中文  Dropdown Arrow
欢迎您 登录
Int32 结构
表示 32 位有符号的整数。

命名空间: System
程序集: mscorlib(在 mscorlib.dll 中)

Visual Basic(声明)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Structure Int32
    Implements IComparable, IFormattable, IConvertible, IComparable(Of Integer), _
    IEquatable(Of Integer)
Visual Basic (用法)
Dim instance As Integer
C#
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public struct Int32 : IComparable, IFormattable, IConvertible, 
    IComparable<int>, IEquatable<int>
C++
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public value class Int32 : IComparable, IFormattable, IConvertible, 
    IComparable<int>, IEquatable<int>
J#
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public final class Int32 extends ValueType implements IComparable, IFormattable, 
    IConvertible, IComparable<int>, IEquatable<int>
JScript
XAML
不适用。

Int32 值类型表示值介于 -2,147,483,648 到 +2,147,483,647 之间的有符号整数。

Int32 为比较该类型的实例、将实例值转换为它的 String 表示形式以及将数字的 String 表示形式转换为该类型的实例提供了相应的方法。

有关格式规范代码如何控制值类型的 String 表示形式的信息,请参见 格式化概述

此类型实现 IComparableIComparableIFormattableIConvertible 接口。使用 Convert 类进行转换,而不是使用此类型的 IConvertible 显式接口成员实现。

此类型的所有成员都是线程安全的。看似修改了实例状态的成员实际上返回一个用新值实例化的新实例。正如对任何其他类型一样,对于包含此类型的实例的共享变量,也必须通过锁定来保护对其进行的读写,以保证实现线程安全。

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

Windows Vista、Microsoft Windows XP SP2 和 Windows Server 2003 SP1 支持 Microsoft .NET Framework 3.0。

.NET Framework

受以下版本支持:3.0、2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

XNA Framework

受以下版本支持:1.0
Page view tracker

<script src="http://i2.msdn.microsoft.com/Platform/Controls/WebTrends/resources/webtrendsscript-bn2008.3.js" type=text/javascript></script>

DCSIMG
<script src="http://i2.msdn.microsoft.com/zh-cn/mtps-bn2008.3.js?l=zh-cn&i=&ct=CodeSnippet;CollapsibleArea;Eyebrow;Footer;InteractiveToolbar;iRootBrand;KTableControl;LocaleManagementFlyout;Masthead;MtpsLoginStatus;QuickLinksFlyout;Search;SurveyLauncher;TabStrip;TemplatedFlyout;UserRecognition;WebMetrix;WebTrends" type=text/javascript></script> <script type=text/javascript> // </script> <script type=text/javascript> // </script>
<script language=javascript src="http://js.microsoft.com/library/svy/sto/broker.js" type=text/javascript></script> <script language=JavaScript src="http://js.microsoft.com/library/svy/sto/SiteRecruit_PageConfiguration_MSDN-p15808382mt-289.js"></script>

Page view tracker
<script src="http://i2.technet.microsoft.com/Platform/Controls/WebTrends/resources/webtrendsscript-bn2008.3.js" type=text/javascript></script> <script src="http://i2.technet.microsoft.com/zh-cn/sysinternals/mtps-bn2008.3.js?l=zh-cn&i=sysinternals&ct=CodeSnippet;CollapsibleArea;Eyebrow;Footer;InteractiveToolbar;iRootBrand;KTableControl;LocaleManagementFlyout;Masthead;MtpsLoginStatus;QuickLinksFlyout;Search;SurveyLauncher;TabStrip;TemplatedFlyout;UserRecognition;WebMetrix;WebTrends" type=text/javascript></script> <script type=text/javascript> // </script> <script type=text/javascript> // </script>
<script language=javascript src="http://js.microsoft.com/library/svy/sto/broker.js" type=text/javascript></script> <script language=JavaScript src="http://js.microsoft.com/library/svy/sto/SiteRecruit_PageConfiguration_TN-p15808382mt-290.js"></script>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页