Single Single Single Single Struct

定義

表示單精確度浮點數。Represents a single-precision floating-point number.

public value class Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public struct Single : IComparable, IComparable<float>, IConvertible, IEquatable<float>, IFormattable
type single = struct
    interface IFormattable
    interface IConvertible
Public Structure Single
Implements IComparable, IComparable(Of Single), IConvertible, IEquatable(Of Single), IFormattable
繼承
屬性
實作

備註

Single實值型別與值範圍從負 3.402823e38 到正 3.402823 e 38,以及正或負零,表示單精確度 32 位元數字PositiveInfinityNegativeInfinity,並不是數字 (NaN)。The Single value type represents a single-precision 32-bit number with values ranging from negative 3.402823e38 to positive 3.402823e38, as well as positive or negative zero, PositiveInfinity, NegativeInfinity, and not a number (NaN). 它被用來代表的值,是極大 (例如行星或個之間的距離) 或極小 (例如在公斤物質分子大量) 和,通常是不精確 (例如從地球的距離,以另一個太陽系).It is intended to represent values that are extremely large (such as distances between planets or galaxies) or extremely small (such as the molecular mass of a substance in kilograms) and that often are imprecise (such as the distance from earth to another solar system). Single類型符合 IEC 60559:1989 (IEEE 754) 二進位浮點運算的標準。The Single type complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.

本主題包含下列章節:This topic consists of the following sections:

System.Single 提供方法來比較此類型的執行個體值轉換成其字串表示,並將數字的字串表示轉換成此型別的執行個體的執行個體。System.Single provides methods to compare instances of this type, to convert the value of an instance to its string representation, and to convert the string representation of a number to an instance of this type. 格式規格的程式碼的實值類型的字串表示的控制方式的相關資訊,請參閱格式化型別標準數值格式字串,和自訂數值格式字串For information about how format specification codes control the string representation of value types, see Formatting Types, Standard Numeric Format Strings, and Custom Numeric Format Strings.

浮點數表示和有效位數Floating-point representation and precision

Single資料類型會儲存 32 位元的二進位格式,單精確度浮點值下表所示:The Single data type stores single-precision floating-point values in a 32-bit binary format, as shown in the following table:

組件Part BitsBits
有效數字或尾數Significand or mantissa 0-220-22
指數Exponent 23-3023-30
符號 (0 = 正數、 1 = 負)Sign (0 = positive, 1 = negative) 3131

如同小數無法精確地表示有些小數值 (例如 1/3 或Math.PI),二進位分數是無法代表某些小數的值。Just as decimal fractions are unable to precisely represent some fractional values (such as 1/3 or Math.PI), binary fractions are unable to represent some fractional values. 例如,2/10,精確地由.2 以小數表示,被以.0011111001001100 為二進位分數,使用模式"1100"重複為無限大。For example, 2/10, which is represented precisely by .2 as a decimal fraction, is represented by .0011111001001100 as a binary fraction, with the pattern "1100" repeating to infinity. 在此情況下,浮點值會提供它所代表的數字不精確表示法。In this case, the floating-point value provides an imprecise representation of the number that it represents. 經常執行額外的數學運算的原始浮點數的值會增加其缺乏精確度。Performing additional mathematical operations on the original floating-point value often increases its lack of precision. 比方說,如果您要比較和.3 10 兩者相乘的結果,而新增至.3.3 九次,您會看到該加法會產生較不精確的結果,因為它牽涉到比乘法的八個其他作業。For example, if you compare the results of multiplying .3 by 10 and adding .3 to .3 nine times, you will see that addition produces the less precise result, because it involves eight more operations than multiplication. 請注意,此差異是只有當您顯示兩個明顯Single使用"R"的值標準數值格式字串,而如果有必要時,會顯示所有支援的有效位數的 9 位數Single型別。Note that this disparity is apparent only if you display the two Single values by using the "R" standard numeric format string, which, if necessary, displays all 9 digits of precision supported by the Single type.

using System;

public class Example
{
   public static void Main()
   {
      Single value = .2f;
      Single result1 = value * 10f;
      Single result2 = 0f;
      for (int ctr = 1; ctr <= 10; ctr++)
         result2 += value;

      Console.WriteLine(".2 * 10:           {0:R}", result1);
      Console.WriteLine(".2 Added 10 times: {0:R}", result2);
   }
}
// The example displays the following output:
//       .2 * 10:           2
//       .2 Added 10 times: 2.00000024
Module Example
   Public Sub Main()
      Dim value As Single = .2
      Dim result1 As Single = value * 10
      Dim result2 As Single
      For ctr As Integer = 1 To 10
         result2 += value
      Next
      Console.WriteLine(".2 * 10:           {0:R}", result1)
      Console.WriteLine(".2 Added 10 times: {0:R}", result2)
   End Sub
End Module
' The example displays the following output:
'       .2 * 10:           2
'       .2 Added 10 times: 2.00000024

因為小的二進位數值無法完全代表一些數字,浮點數可以只近似實際數字。Because some numbers cannot be represented exactly as fractional binary values, floating-point numbers can only approximate real numbers.

所有的浮點數具有有限的數目的有效位數,其中也會決定如何精確的浮點值接近實際數字。All floating-point numbers have a limited number of significant digits, which also determines how accurately a floating-point value approximates a real number. ASingle值具有最多 7 的有效位數的十進位數字,雖然內部維護最多 9 位數。A Single value has up to 7 decimal digits of precision, although a maximum of 9 digits is maintained internally. 這表示某些浮點運算可能缺少若要變更的浮點值的有效位數。This means that some floating-point operations may lack the precision to change a floating-point value. 下列範例定義大的單精確度浮點數值,,然後新增 乘積Single.Epsilon和它的其中一個大關。The following example defines a large single-precision floating-point value, and then adds the product of Single.Epsilon and one quadrillion to it. 不過,產品會太小,無法修改原始的浮點值。However, the product is too small to modify the original floating-point value. 其最小顯著性數字是千分之一秒,而中產品的最高有效位數是 10-30Its least significant digit is thousandths, whereas the most significant digit in the product is 10-30.

using System;

public class Example
{
   public static void Main()
   {
      Single value = 123.456f;
      Single additional = Single.Epsilon * 1e15f;
      Console.WriteLine($"{value} + {additional} = {value + additional}");
   }
}
// The example displays the following output:
//    123.456 + 1.401298E-30 = 123.456
Module Example
   Public Sub Main()
      Dim value As Single = 123.456
      Dim additional As Single = Single.Epsilon * 1e15
      Console.WriteLine($"{value} + {additional} = {value + additional}")
   End Sub
End Module
' The example displays the following output:
'   123.456 + 1.401298E-30 = 123.456

浮點數限制有效位數有數個結果:The limited precision of a floating-point number has several consequences:

  • 因為其最小有效位數不同,會出現特定的有效位數相等的兩個浮點數可能不比較相等。Two floating-point numbers that appear equal for a particular precision might not compare equal because their least significant digits are different. 在下列範例中,一系列數字加在一起,,以及其總計相較於其預期的總和。In the following example, a series of numbers are added together, and their total is compared with their expected total. 雖然兩個值會出現相同,呼叫Equals方法表示它們不是。Although the two values appear to be the same, a call to the Equals method indicates that they are not.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Single[] values = { 10.01f, 2.88f, 2.88f, 2.88f, 9.0f };
          Single result = 27.65f;
          Single total = 0f;
          foreach (var value in values)
             total += value;
    
          if (total.Equals(result))
             Console.WriteLine("The sum of the values equals the total.");
          else
             Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).",
                               total, result); 
       }
    }
    // The example displays the following output:
    //      The sum of the values (27.65) does not equal the total (27.65).   
    //
    // If the index items in the Console.WriteLine statement are changed to {0:R},
    // the example displays the following output:
    //       The sum of the values (27.6500015) does not equal the total (27.65).   
    
    Module Example
       Public Sub Main()
          Dim values() As Single = { 10.01, 2.88, 2.88, 2.88, 9.0 }
          Dim result As Single = 27.65
          Dim total As Single
          For Each value In values
             total += value
          Next
          If total.Equals(result) Then
             Console.WriteLine("The sum of the values equals the total.")
          Else
             Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).",
                               total, result) 
          End If     
       End Sub
    End Module
    ' The example displays the following output:
    '      The sum of the values (27.65) does not equal the total (27.65).   
    '
    ' If the index items in the Console.WriteLine statement are changed to {0:R},
    ' the example displays the following output:
    '       The sum of the values (27.639999999999997) does not equal the total (27.64).   
    

    如果您變更中的格式項目Console.WriteLine(String, Object, Object)陳述式,從{0}{1}{0:R}{1:R}以顯示所有的有效位數,兩個Single很清楚兩個值相等的值,因為失去了在加法作業期間的有效位數。If you change the format items in the Console.WriteLine(String, Object, Object) statement from {0} and {1} to {0:R} and {1:R} to display all significant digits of the two Single values, it is clear that the two values are unequal because of a loss of precision during the addition operations. 在此情況下,解決問題,藉由呼叫Math.Round(Double, Int32)要捨入方法Single到所需的精確度,然後再執行比較的值。In this case, the issue can be resolved by calling the Math.Round(Double, Int32) method to round the Single values to the desired precision before performing the comparison.

  • 使用浮點數數學或比較運算可能不會產生相同的結果使用十進位數字時,如果因為二進位浮點數可能不等於的十進位數字。A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used, because the binary floating-point number might not equal the decimal number. 上述範例說明這顯示結果乘以.3 10,並加入至.3.3 九次。A previous example illustrated this by displaying the result of multiplying .3 by 10 and adding .3 to .3 nine times.

    重要的小數值與數值運算精確度時,請使用Decimal類型,而非Single型別。When accuracy in numeric operations with fractional values is important, use the Decimal type instead of the Single type. 當數字的操作,具有超過範圍的整數值的精確度Int64UInt64型別是重要的是,使用BigInteger型別。When accuracy in numeric operations with integral values beyond the range of the Int64 or UInt64 types is important, use the BigInteger type.

  • 值可能不會反覆存取如果牽涉到浮點數。A value might not round-trip if a floating-point number is involved. 如果作業會將原始浮點數轉換成另一種形式,反運算將轉換回浮點數,轉換的形式,而且最終浮點數等於原始值,即稱為反覆存取浮點數。A value is said to round-trip if an operation converts an original floating-point number to another form, an inverse operation transforms the converted form back to a floating-point number, and the final floating-point number is equal to the original floating-point number. 來回行程可能會失敗,因為一或多個最低有效位數遺失或轉換變更。The round trip might fail because one or more least significant digits are lost or changed in a conversion. 在下列範例中,三個Single值被轉換成字串並儲存在檔案中。In the following example, three Single values are converted to strings and saved in a file. 如輸出所示,雖然值看起來相同,則還原的值不相等為原始值。As the output shows, although the values appear to be identical, the restored values are not equal to the original values.

    using System;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          StreamWriter sw = new StreamWriter(@".\Singles.dat");
          Single[] values = { 3.2f/1.11f, 1.0f/3f, (float) Math.PI };
          for (int ctr = 0; ctr < values.Length; ctr++) {
             sw.Write(values[ctr].ToString());
             if (ctr != values.Length - 1)
                sw.Write("|");
          }      
          sw.Close();
          
          Single[] restoredValues = new Single[values.Length];
          StreamReader sr = new StreamReader(@".\Singles.dat");
          string temp = sr.ReadToEnd();
          string[] tempStrings = temp.Split('|');
          for (int ctr = 0; ctr < tempStrings.Length; ctr++)
             restoredValues[ctr] = Single.Parse(tempStrings[ctr]);   
    
    
          for (int ctr = 0; ctr < values.Length; ctr++)
             Console.WriteLine("{0} {2} {1}", values[ctr], 
                               restoredValues[ctr],
                               values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>");
       }
    }
    // The example displays the following output:
    //       2.882883 <> 2.882883
    //       0.3333333 <> 0.3333333
    //       3.141593 <> 3.141593
    
    Imports System.IO
    
    Module Example
       Public Sub Main()
          Dim sw As New StreamWriter(".\Singles.dat")
          Dim values() As Single = { 3.2/1.11, 1.0/3, CSng(Math.PI)  }
          For ctr As Integer = 0 To values.Length - 1
             sw.Write(values(ctr).ToString())
             If ctr <> values.Length - 1 Then sw.Write("|")
          Next      
          sw.Close()
          
          Dim restoredValues(values.Length - 1) As Single
          Dim sr As New StreamReader(".\Singles.dat")
          Dim temp As String = sr.ReadToEnd()
          Dim tempStrings() As String = temp.Split("|"c)
          For ctr As Integer = 0 To tempStrings.Length - 1
             restoredValues(ctr) = Single.Parse(tempStrings(ctr))   
          Next 
    
          For ctr As Integer = 0 To values.Length - 1
             Console.WriteLine("{0} {2} {1}", values(ctr), 
                               restoredValues(ctr),
                               If(values(ctr).Equals(restoredValues(ctr)), "=", "<>"))
          Next
       End Sub
    End Module
    ' The example displays the following output:
    '        2.882883 <> 2.882883
    '        0.3333333 <> 0.3333333
    '        3.141593 <> 3.141593
    

    在此情況下,值可以是成功的來回時間使用"G9"標準數值格式字串保留完整的有效位數的Single值,如下列範例所示。In this case, the values can be successfully round-tripped by using the "G9" standard numeric format string to preserve the full precision of Single values, as the following example shows.

    using System;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          StreamWriter sw = new StreamWriter(@".\Singles.dat");
          Single[] values = { 3.2f/1.11f, 1.0f/3f, (float) Math.PI };
          for (int ctr = 0; ctr < values.Length; ctr++) 
             sw.Write("{0:G9}{1}", values[ctr], ctr < values.Length - 1 ? "|" : "" );
          
          sw.Close();
          
          Single[] restoredValues = new Single[values.Length];
          StreamReader sr = new StreamReader(@".\Singles.dat");
          string temp = sr.ReadToEnd();
          string[] tempStrings = temp.Split('|');
          for (int ctr = 0; ctr < tempStrings.Length; ctr++)
             restoredValues[ctr] = Single.Parse(tempStrings[ctr]);   
    
    
          for (int ctr = 0; ctr < values.Length; ctr++)
             Console.WriteLine("{0} {2} {1}", values[ctr], 
                               restoredValues[ctr],
                               values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>");
       }
    }
    // The example displays the following output:
    //       2.882883 = 2.882883
    //       0.3333333 = 0.3333333
    //       3.141593 = 3.141593
    
    Imports System.IO
    
    Module Example
       Public Sub Main()
          Dim sw As New StreamWriter(".\Singles.dat")
          Dim values() As Single = { 3.2/1.11, 1.0/3, CSng(Math.PI)  }
          For ctr As Integer = 0 To values.Length - 1
             sw.Write("{0:G9}{1}", values(ctr), 
                      If(ctr < values.Length - 1, "|", ""))
          Next      
          sw.Close()
          
          Dim restoredValues(values.Length - 1) As Single
          Dim sr As New StreamReader(".\Singles.dat")
          Dim temp As String = sr.ReadToEnd()
          Dim tempStrings() As String = temp.Split("|"c)
          For ctr As Integer = 0 To tempStrings.Length - 1
             restoredValues(ctr) = Single.Parse(tempStrings(ctr))   
          Next 
    
          For ctr As Integer = 0 To values.Length - 1
             Console.WriteLine("{0} {2} {1}", values(ctr), 
                               restoredValues(ctr),
                               If(values(ctr).Equals(restoredValues(ctr)), "=", "<>"))
          Next
       End Sub
    End Module
    ' The example displays the following output:
    '       2.882883 = 2.882883
    '       0.3333333 = 0.3333333
    '       3.141593 = 3.141593
    
  • Single 值有較少精確度卻高於Double值。Single values have less precision than Double values. ASingle值轉換成看似相當Double通常不等於Double因為有效位數的差異值。A Single value that is converted to a seemingly equivalent Double often does not equal the Double value because of differences in precision. 在下列範例中,相同的除法運算的結果指派給Double值和Single值。In the following example, the result of identical division operations is assigned to a Double value and a Single value. 在後Single的值轉換為Double,比較兩個值會顯示不相等。After the Single value is cast to a Double, a comparison of the two values shows that they are unequal.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Double value1 = 1/3.0;
          Single sValue2 = 1/3.0f;
          Double value2 = (Double) sValue2;
          Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, 
                                              value1.Equals(value2));
       }
    }
    // The example displays the following output:
    //        0.33333333333333331 = 0.3333333432674408: False
    
    Module Example
       Public Sub Main()
          Dim value1 As Double = 1/3
          Dim sValue2 As Single = 1/3
          Dim value2 As Double = CDbl(sValue2)
          Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2))
       End Sub
    End Module
    ' The example displays the following output:
    '       0.33333333333333331 = 0.3333333432674408: False
    

    若要避免這個問題,請使用Double資料類型的位置Single資料類型或使用Round方法,讓這兩個值具有相同的有效位數。To avoid this problem, either use the Double data type in place of the Single data type, or use the Round method so that both values have the same precision.

測試相等Testing for equality

若要才會被視為相等,兩個Single值必須代表相同的值。To be considered equal, two Single values must represent identical values. 不過,因為在精確度值之間的差異,或因為遺失一或兩個值的有效位數,應該通常是相同的浮點值變得不相等,因為其最小有效位數的差異。However, because of differences in precision between values, or because of a loss of precision by one or both values, floating-point values that are expected to be identical often turn out to be unequal due to differences in their least significant digits. 如此一來,呼叫Equals方法,以判斷兩個值是否相等或呼叫CompareTo方法,以判斷兩個之間的關聯性Single值,通常會產生非預期的結果。As a result, calls to the Equals method to determine whether two values are equal, or calls to the CompareTo method to determine the relationship between two Single values, often yield unexpected results. 這是出現在下列範例中,其中兩個明顯等於Single值變得不相等,因為第一個值具有 7 位數的有效位數,而第二個值具有 9。This is evident in the following example, where two apparently equal Single values turn out to be unequal, because the first value has 7 digits of precision, whereas the second value has 9.

using System;

public class Example
{
   public static void Main()
   {
      float value1 = .3333333f;
      float value2 = 1.0f/3;
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2));
   }
}
// The example displays the following output:
//        0.3333333 = 0.333333343: False
Module Example
   Public Sub Main()
      Dim value1 As Single = .3333333
      Dim value2 As Single = 1/3
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2))
   End Sub
End Module
' The example displays the following output:
'       0.3333333 = 0.333333343: False

導出的值,通常當做不同的方式,遵循不同的程式碼路徑,並且證明不相等。Calculated values that follow different code paths and that are manipulated in different ways often prove to be unequal. 在下列範例中,一個Single平方值,並計算再還原為原始值的平方根。In the following example, one Single value is squared, and then the square root is calculated to restore the original value. 第二個Single會乘以 3.51 和平方之前 3.51 還原為原始值除以結果的平方根。A second Single is multiplied by 3.51 and squared before the square root of the result is divided by 3.51 to restore the original value. 雖然兩個值看起來相同,但呼叫Equals(Single)方法指出它們是否不相等。Although the two values appear to be identical, a call to the Equals(Single) method indicates that they are not equal. 使用"G9"標準格式字串,以傳回結果字串會顯示每個的所有有效位數Single值會顯示第二個值是.0000000000001 第一個大於或等於。Using the "G9" standard format string to return a result string that displays all the significant digits of each Single value shows that the second value is .0000000000001 less than the first.

using System;

public class Example
{
   public static void Main()
   {
      float value1 = 10.201438f;
      value1 = (float) Math.Sqrt((float) Math.Pow(value1, 2));
      float value2 = (float) Math.Pow((float) value1 * 3.51f, 2);
      value2 = ((float) Math.Sqrt(value2)) / 3.51f;
      Console.WriteLine("{0} = {1}: {2}\n", 
                        value1, value2, value1.Equals(value2)); 
      Console.WriteLine("{0:G9} = {1:G9}", value1, value2); 
   }
}
// The example displays the following output:
//       10.20144 = 10.20144: False
//       
//       10.201438 = 10.2014389
Module Example
   Public Sub Main()
      Dim value1 As Single = 10.201438
      value1 = CSng(Math.Sqrt(CSng(Math.Pow(value1, 2))))
      Dim value2 As Single = CSng(Math.Pow(value1 * CSng(3.51), 2))
      value2 = CSng(Math.Sqrt(value2) / CSng(3.51))
      Console.WriteLine("{0} = {1}: {2}", 
                        value1, value2, value1.Equals(value2)) 
      Console.WriteLine()
      Console.WriteLine("{0:G9} = {1:G9}", value1, value2) 
   End Sub
End Module
' The example displays the following output:
'       10.20144 = 10.20144: False
'       
'       10.201438 = 10.2014389

中的情況下遺失有效位數可能會影響比較的結果,您可以使用下列技術,而不是呼叫EqualsCompareTo方法:In cases where a loss of precision is likely to affect the result of a comparison, you can use the following techniques instead of calling the Equals or CompareTo method:

  • 呼叫Math.Round方法,以確保這兩個值都有相同的精確度。Call the Math.Round method to ensure that both values have the same precision. 下列範例會修改先前的範例,為使用這種方法,讓兩個小數值相等。The following example modifies a previous example to use this approach so that two fractional values are equivalent.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          float value1 = .3333333f;
          float value2 = 1.0f/3;
          int precision = 7;
          value1 = (float) Math.Round(value1, precision);
          value2 = (float) Math.Round(value2, precision);
          Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2));
       }
    }
    // The example displays the following output:
    //        0.3333333 = 0.3333333: True
    
    Module Example
       Public Sub Main()
          Dim value1 As Single = .3333333
          Dim value2 As Single = 1/3
          Dim precision As Integer = 7
          value1 = CSng(Math.Round(value1, precision))
          value2 = CSng(Math.Round(value2, precision))
          Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2))
       End Sub
    End Module
    ' The example displays the following output:
    '       0.3333333 = 0.3333333: True
    

    請注意,有效位數的問題仍適用於的中點值捨入。Note that the problem of precision still applies to rounding of midpoint values. 如需詳細資訊,請參閱 Math.Round(Double, Int32, MidpointRounding) 方法。For more information, see the Math.Round(Double, Int32, MidpointRounding) method.

  • 近似相等,而不是等號比較測試。Test for approximate equality instead of equality. 這項技術會要求您定義的其中一個絕對數量的兩個值可以用不同,但仍視為相等,或您定義相對量的較小的值可以偏離較大的值。This technique requires that you define either an absolute amount by which the two values can differ but still be equal, or that you define a relative amount by which the smaller value can diverge from the larger value.

    警告

    Single.Epsilon 有時會作為兩個之間距離的絕對單位Single值時測試是否相等。Single.Epsilon is sometimes used as an absolute measure of the distance between two Single values when testing for equality. 不過,Single.Epsilon測量的最小的可能值,可以新增或減去,Single其值為零。However, Single.Epsilon measures the smallest possible value that can be added to, or subtracted from, a Single whose value is zero. 為大部分的正數和負數Single的值,而值Single.Epsilon太小而無法偵測到。For most positive and negative Single values, the value of Single.Epsilon is too small to be detected. 因此,除了為零的值,我們不建議在測試相等。Therefore, except for values that are zero, we do not recommend its use in tests for equality.

    下列範例會使用第二種方法來定義IsApproximatelyEqual方法,來測試兩個值之間的相對差異。The following example uses the latter approach to define an IsApproximatelyEqual method that tests the relative difference between two values. 它也會對照的呼叫結果IsApproximatelyEqual方法和Equals(Single)方法。It also contrasts the result of calls to the IsApproximatelyEqual method and the Equals(Single) method.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          float one1 = .1f * 10;
          float one2 = 0f;
          for (int ctr = 1; ctr <= 10; ctr++)
             one2 += .1f;
    
          Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2));
          Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", 
                            one1, one2, 
                            IsApproximatelyEqual(one1, one2, .000001f));   
       }
    
       static bool IsApproximatelyEqual(float value1, float value2, float epsilon)
       {
          // If they are equal anyway, just return True.
          if (value1.Equals(value2))
             return true;
    
          // Handle NaN, Infinity.
          if (Double.IsInfinity(value1) | Double.IsNaN(value1))
             return value1.Equals(value2);
          else if (Double.IsInfinity(value2) | Double.IsNaN(value2))
             return value1.Equals(value2);
    
          // Handle zero to avoid division by zero
          double divisor = Math.Max(value1, value2);
          if (divisor.Equals(0)) 
             divisor = Math.Min(value1, value2);
          
          return Math.Abs(value1 - value2)/divisor <= epsilon;           
       } 
    }
    // The example displays the following output:
    //       1 = 1.00000012: False
    //       1 is approximately equal to 1.00000012: True
    
    Module Example
       Public Sub Main()
          Dim one1 As Single = .1 * 10
          Dim one2 As Single = 0
          For ctr As Integer = 1 To 10
             one2 += CSng(.1)
          Next
          Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2))
          Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", 
                            one1, one2, 
                            IsApproximatelyEqual(one1, one2, .000001))   
       End Sub
    
       Function IsApproximatelyEqual(value1 As Single, value2 As Single, 
                                     epsilon As Single) As Boolean
          ' If they are equal anyway, just return True.
          If value1.Equals(value2) Then Return True
          
          ' Handle NaN, Infinity.
          If Single.IsInfinity(value1) Or Single.IsNaN(value1) Then
             Return value1.Equals(value2)
          Else If Single.IsInfinity(value2) Or Single.IsNaN(value2)
             Return value1.Equals(value2)
          End If
          
          ' Handle zero to avoid division by zero
          Dim divisor As Single = Math.Max(value1, value2)
          If divisor.Equals(0) Then
             divisor = Math.Min(value1, value2)
          End If 
          
          Return Math.Abs(value1 - value2)/divisor <= epsilon           
       End Function
    End Module
    ' The example displays the following output:
    '       1 = 1.00000012: False
    '       1 is approximately equal to 1.00000012: True
    

浮點值和例外狀況Floating-point values and exceptions

具有浮點值的作業不會擲回例外狀況,與作業和不合法的作業,例如部門的情況下擲回例外狀況,由零或溢位的整數型別不同。Operations with floating-point values do not throw exceptions, unlike operations with integral types, which throw exceptions in cases of illegal operations such as division by zero or overflow. 相反地,在這些情況下,浮點運算的結果是零,正無限大、 負無限大或不是數字 (NaN):Instead, in these situations, the result of a floating-point operation is zero, positive infinity, negative infinity, or not a number (NaN):

  • 如果浮點運算的結果太小,目的格式,則結果會是零。If the result of a floating-point operation is too small for the destination format, the result is zero. 這可能會乘以兩個非常小的浮點數,如下列範例所示。This can occur when two very small floating-point numbers are multiplied, as the following example shows.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          float value1 = 1.163287e-36f;
          float value2 = 9.164234e-25f;
          float result = value1 * value2;
          Console.WriteLine("{0} * {1} = {2}", value1, value2, result);
          Console.WriteLine("{0} = 0: {1}", result, result.Equals(0.0f));
       }
    }
    // The example displays the following output:
    //       1.163287E-36 * 9.164234E-25 = 0
    //       0 = 0: True
    
    Module Example
       Public Sub Main()
          Dim value1 As Single = 1.163287e-36
          Dim value2 As Single = 9.164234e-25
          Dim result As Single = value1 * value2
          Console.WriteLine("{0} * {1} = {2:R}", value1, value2, result)
          Console.WriteLine("{0} = 0: {1}", result, result.Equals(0))
       End Sub
    End Module
    ' The example displays the following output:
    '       1.163287E-36 * 9.164234E-25 = 0
    '       0 = 0: True
    
  • 浮點運算的結果大小超過目的格式的範圍,作業的結果是否PositiveInfinityNegativeInfinity視需要結果的正負號。If the magnitude of the result of a floating-point operation exceeds the range of the destination format, the result of the operation is PositiveInfinity or NegativeInfinity, as appropriate for the sign of the result. 溢位運算的結果Single.MaxValuePositiveInfinity,並造成溢位運算的結果Single.MinValueNegativeInfinity,如下列範例所示。The result of an operation that overflows Single.MaxValue is PositiveInfinity, and the result of an operation that overflows Single.MinValue is NegativeInfinity, as the following example shows.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          float value1 = 3.065e35f;
          float value2 = 6.9375e32f;
          float result = value1 * value2;
          Console.WriteLine("PositiveInfinity: {0}", 
                             Single.IsPositiveInfinity(result));
          Console.WriteLine("NegativeInfinity: {0}\n", 
                            Single.IsNegativeInfinity(result));
    
          value1 = -value1;
          result = value1 * value2;
          Console.WriteLine("PositiveInfinity: {0}", 
                             Single.IsPositiveInfinity(result));
          Console.WriteLine("NegativeInfinity: {0}", 
                            Single.IsNegativeInfinity(result));
       }
    }                                                                 
    
    // The example displays the following output:
    //       PositiveInfinity: True
    //       NegativeInfinity: False
    //       
    //       PositiveInfinity: False
    //       NegativeInfinity: True
    
    Module Example
       Public Sub Main()
          Dim value1 As Single = 3.065e35
          Dim value2 As Single = 6.9375e32
          Dim result As Single = value1 * value2
          Console.WriteLine("PositiveInfinity: {0}", 
                             Single.IsPositiveInfinity(result))
          Console.WriteLine("NegativeInfinity: {0}", 
                            Single.IsNegativeInfinity(result))
          Console.WriteLine()                  
          value1 = -value1
          result = value1 * value2
          Console.WriteLine("PositiveInfinity: {0}", 
                             Single.IsPositiveInfinity(result))
          Console.WriteLine("NegativeInfinity: {0}", 
                            Single.IsNegativeInfinity(result))
       End Sub
    End Module
    ' The example displays the following output:
    '       PositiveInfinity: True
    '       NegativeInfinity: False
    '       
    '       PositiveInfinity: False
    '       NegativeInfinity: True
    

    PositiveInfinity 也產生除以零正值被除數,與和NegativeInfinity除法運算結果與負被除數為零。PositiveInfinity also results from a division by zero with a positive dividend, and NegativeInfinity results from a division by zero with a negative dividend.

  • 如果浮點運算無效,作業的結果是NaNIf a floating-point operation is invalid, the result of the operation is NaN. 比方說,NaN天時,下列作業:For example, NaN results from the following operations:

    • 除數為零與被除數為零。Division by zero with a dividend of zero. 請注意除法的其他情況下,在零結果PositiveInfinityNegativeInfinityNote that other cases of division by zero result in either PositiveInfinity or NegativeInfinity.

    • 無效的輸入與任何浮點運算。Any floating-point operation with invalid input. 例如,嘗試尋找為負數值的平方根傳回NaNFor example, attempting to find the square root of a negative value returns NaN.

    • 使用引數,其值的任何作業Single.NaNAny operation with an argument whose value is Single.NaN.

型別轉換和單一結構Type conversions and the Single structure

Single結構並未定義任何明確或隱含的轉換運算子; 相反地,轉換會由編譯器實作。The Single structure does not define any explicit or implicit conversion operators; instead, conversions are implemented by the compiler.

下表列出可能的轉換值的其他基本數值類型到Single值,它也會指出是否會在加寬或縮小的轉換,以及是否產生Single可能會有較少精確度卻高於原始值。The following table lists the possible conversions of a value of the other primitive numeric types to a Single value, It also indicates whether the conversion is widening or narrowing and whether the resulting Single may have less precision than the original value.

Conversion from 擴展/縮小Widening/narrowing 可能會遺失有效位數Possible loss of precision
Byte WideningWidening No
Decimal WideningWidening

請注意,C# 需要轉型運算子。Note that C# requires a cast operator.
可以。Yes. Decimal 支援 29 有效小數位數;Single支援 9。Decimal supports 29 decimal digits of precision; Single supports 9.
Double 縮小;範圍外的值會轉換成Double.NegativeInfinityDouble.PositiveInfinityNarrowing; out-of-range values are converted to Double.NegativeInfinity or Double.PositiveInfinity. 可以。Yes. Double 支援 17 位數的有效位數;Single支援 9。Double supports 17 decimal digits of precision; Single supports 9.
Int16 WideningWidening No
Int32 WideningWidening 可以。Yes. Int32 支援 10 個有效小數位數;Single支援 9。Int32 supports 10 decimal digits of precision; Single supports 9.
Int64 WideningWidening 可以。Yes. Int64 支援 19 有效小數位數;Single支援 9。Int64 supports 19 decimal digits of precision; Single supports 9.
SByte WideningWidening No
UInt16 WideningWidening No
UInt32 WideningWidening 可以。Yes. UInt32 支援 10 個有效小數位數;Single支援 9。UInt32 supports 10 decimal digits of precision; Single supports 9.
UInt64 WideningWidening 可以。Yes. Int64 支援 20 位數的有效位數;Single支援 9。Int64 supports 20 decimal digits of precision; Single supports 9.

下列範例會轉換至其他基本數值類型的最小值或最大值Single值。The following example converts the minimum or maximum value of other primitive numeric types to a Single value.

using System;

public class Example
{
   public static void Main()
   {
      dynamic[] values = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
                           Decimal.MaxValue, Double.MinValue, Double.MaxValue,
                           Int16.MinValue, Int16.MaxValue, Int32.MinValue,
                           Int32.MaxValue, Int64.MinValue, Int64.MaxValue,
                           SByte.MinValue, SByte.MaxValue, UInt16.MinValue,
                           UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
                           UInt64.MinValue, UInt64.MaxValue };
      float sngValue;
      foreach (var value in values) {
         if (value.GetType() == typeof(Decimal) ||
             value.GetType() == typeof(Double))
            sngValue = (float) value;
         else
            sngValue = value;
         Console.WriteLine("{0} ({1}) --> {2:R} ({3})",
                           value, value.GetType().Name,
                           sngValue, sngValue.GetType().Name);
      }
   }
}
// The example displays the following output:
//       0 (Byte) --> 0 (Single)
//       255 (Byte) --> 255 (Single)
//       -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
//       79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
//       -1.79769313486232E+308 (Double) --> -Infinity (Single)
//       1.79769313486232E+308 (Double) --> Infinity (Single)
//       -32768 (Int16) --> -32768 (Single)
//       32767 (Int16) --> 32767 (Single)
//       -2147483648 (Int32) --> -2.14748365E+09 (Single)
//       2147483647 (Int32) --> 2.14748365E+09 (Single)
//       -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
//       9223372036854775807 (Int64) --> 9.223372E+18 (Single)
//       -128 (SByte) --> -128 (Single)
//       127 (SByte) --> 127 (Single)
//       0 (UInt16) --> 0 (Single)
//       65535 (UInt16) --> 65535 (Single)
//       0 (UInt32) --> 0 (Single)
//       4294967295 (UInt32) --> 4.2949673E+09 (Single)
//       0 (UInt64) --> 0 (Single)
//       18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)
Module Example
   Public Sub Main()
      Dim values() As Object = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
                                 Decimal.MaxValue, Double.MinValue, Double.MaxValue,
                                 Int16.MinValue, Int16.MaxValue, Int32.MinValue,
                                 Int32.MaxValue, Int64.MinValue, Int64.MaxValue,
                                 SByte.MinValue, SByte.MaxValue, UInt16.MinValue,
                                 UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
                                 UInt64.MinValue, UInt64.MaxValue }
      Dim sngValue As Single
      For Each value In values
         If value.GetType() = GetType(Double) Then
            sngValue = CSng(value)
         Else
            sngValue = value
         End If
         Console.WriteLine("{0} ({1}) --> {2:R} ({3})",
                           value, value.GetType().Name,
                           sngValue, sngValue.GetType().Name)
      Next
   End Sub
End Module
' The example displays the following output:
'       0 (Byte) --> 0 (Single)
'       255 (Byte) --> 255 (Single)
'       -79228162514264337593543950335 (Decimal) --> -7.92281625E+28 (Single)
'       79228162514264337593543950335 (Decimal) --> 7.92281625E+28 (Single)
'       -1.79769313486232E+308 (Double) --> -Infinity (Single)
'       1.79769313486232E+308 (Double) --> Infinity (Single)
'       -32768 (Int16) --> -32768 (Single)
'       32767 (Int16) --> 32767 (Single)
'       -2147483648 (Int32) --> -2.14748365E+09 (Single)
'       2147483647 (Int32) --> 2.14748365E+09 (Single)
'       -9223372036854775808 (Int64) --> -9.223372E+18 (Single)
'       9223372036854775807 (Int64) --> 9.223372E+18 (Single)
'       -128 (SByte) --> -128 (Single)
'       127 (SByte) --> 127 (Single)
'       0 (UInt16) --> 0 (Single)
'       65535 (UInt16) --> 65535 (Single)
'       0 (UInt32) --> 0 (Single)
'       4294967295 (UInt32) --> 4.2949673E+09 (Single)
'       0 (UInt64) --> 0 (Single)
'       18446744073709551615 (UInt64) --> 1.84467441E+19 (Single)

颾魤 ㄛDoubleDouble.NaNDouble.PositiveInfinity,以及Double.NegativeInfinity轉換到Single.NaNSingle.PositiveInfinity,和Single.NegativeInfinity分別。In addition, the Double values Double.NaN, Double.PositiveInfinity, and Double.NegativeInfinity covert to Single.NaN, Single.PositiveInfinity, and Single.NegativeInfinity, respectively.

請注意,某些數字型別,值的轉換Single值可能會涉及遺失有效位數。Note that the conversion of the value of some numeric types to a Single value can involve a loss of precision. 如範例所示,遺失有效位數時,可能轉換DecimalDoubleInt32Int64UInt32,和UInt64Single值。As the example illustrates, a loss of precision is possible when converting Decimal, Double, Int32, Int64, UInt32, and UInt64 values to Single values.

轉換SingleDouble是擴展轉換。The conversion of a Single value to a Double is a widening conversion. 轉換可能會導致失去精確度如果Double型別沒有的精確表示Single值。The conversion may result in a loss of precision if the Double type does not have a precise representation for the Single value.

轉換Single以外的其他值的任何基本數值資料類型值Double是縮小轉換,而且需要轉換運算子 (在 C# 中) 或轉換方法 (在 Visual Basic)。The conversion of a Single value to a value of any primitive numeric data type other than a Double is a narrowing conversion and requires a cast operator (in C#) or a conversion method (in Visual Basic). 值超出範圍的目標資料類型,都由目標類型的定義MinValueMaxValue屬性,行為如下表所示。Values that are outside the range of the target data type, which are defined by the target type's MinValue and MaxValue properties, behave as shown in the following table.

目標類型Target type 結果Result
任何整數類資料類型Any integral type OverflowException轉換檢查的內容中發生的例外狀況。An OverflowException exception if the conversion occurs in a checked context.

如果在 unchecked 內容中 (C# 中的預設值),就會發生轉換,轉換作業成功,但值溢位。If the conversion occurs in an unchecked context (the default in C#), the conversion operation succeeds but the value overflows.
Decimal OverflowException例外狀況,An OverflowException exception,

颾魤 ㄛ Single.NaNSingle.PositiveInfinity,並Single.NegativeInfinity擲回OverflowExceptionchecked 的內容中,但這些值的溢位時轉換成在 unchecked 內容中的整數的整數的轉換。In addition, Single.NaN, Single.PositiveInfinity, and Single.NegativeInfinity throw an OverflowException for conversions to integers in a checked context, but these values overflow when converted to integers in an unchecked context. 轉換成Decimal,則一律會擲回OverflowExceptionFor conversions to Decimal, they always throw an OverflowException. 轉換成Double,它們會轉換成Double.NaNDouble.PositiveInfinity,和Double.NegativeInfinity分別。For conversions to Double, they convert to Double.NaN, Double.PositiveInfinity, and Double.NegativeInfinity, respectively.

請注意,遺失有效位數可能會使轉換Single成另一個數值類型的值。Note that a loss of precision may result from converting a Single value to another numeric type. 在將非整數的轉換的情況下Single值,如範例輸出所示,小數部分時遺失Single值四捨五入 (就像在 Visual Basic) 或截斷 (例如 C# 中)。In the case of converting non-integral Single values, as the output from the example shows, the fractional component is lost when the Single value is either rounded (as in Visual Basic) or truncated (as in C#). 轉換成Decimal值,Single值不能精確的表示法中的目標資料類型。For conversions to Decimal values, the Single value may not have a precise representation in the target data type.

下列範例會將許多Single數個其他數值類型的值。The following example converts a number of Single values to several other numeric types. 在 Visual Basic (預設值),和在 C# 中檢查的內容中會發生轉換 (因為檢查關鍵字)。The conversions occur in a checked context in Visual Basic (the default) and in C# (because of the checked keyword). 此範例的輸出會顯示轉換的結果中這兩個核取核取的內容。The output from the example shows the result for conversions in both a checked an unchecked context. 您也可以使用編譯在 unchecked 內容中 Visual Basic 中執行的轉換/removeintchecks+編譯器參數和 C# 註解checked陳述式。You can perform conversions in an unchecked context in Visual Basic by compiling with the /removeintchecks+ compiler switch and in C# by commenting out the checked statement.

using System;

public class Example
{
   public static void Main()
   {
      float[] values = { Single.MinValue, -67890.1234f, -12345.6789f,
                         12345.6789f, 67890.1234f, Single.MaxValue,
                         Single.NaN, Single.PositiveInfinity,
                         Single.NegativeInfinity };
      checked {
         foreach (var value in values) {
            try {
                Int64 lValue = (long) value;
                Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                                  value, value.GetType().Name,
                                  lValue, lValue.GetType().Name);
            }
            catch (OverflowException) {
               Console.WriteLine("Unable to convert {0} to Int64.", value);
            }
            try {
                UInt64 ulValue = (ulong) value;
                Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                                  value, value.GetType().Name,
                                  ulValue, ulValue.GetType().Name);
            }
            catch (OverflowException) {
               Console.WriteLine("Unable to convert {0} to UInt64.", value);
            }
            try {
                Decimal dValue = (decimal) value;
                Console.WriteLine("{0} ({1}) --> {2} ({3})",
                                  value, value.GetType().Name,
                                  dValue, dValue.GetType().Name);
            }
            catch (OverflowException) {
               Console.WriteLine("Unable to convert {0} to Decimal.", value);
            }

            Double dblValue = value;
            Console.WriteLine("{0} ({1}) --> {2} ({3})",
                              value, value.GetType().Name,
                              dblValue, dblValue.GetType().Name);
            Console.WriteLine();
         }
      }
   }
}
// The example displays the following output for conversions performed
// in a checked context:
//       Unable to convert -3.402823E+38 to Int64.
//       Unable to convert -3.402823E+38 to UInt64.
//       Unable to convert -3.402823E+38 to Decimal.
//       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
//       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       Unable to convert -67890.13 to UInt64.
//       -67890.13 (Single) --> -67890.12 (Decimal)
//       -67890.13 (Single) --> -67890.125 (Double)
//
//       -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       Unable to convert -12345.68 to UInt64.
//       -12345.68 (Single) --> -12345.68 (Decimal)
//       -12345.68 (Single) --> -12345.6787109375 (Double)
//
//       12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
//       12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
//       12345.68 (Single) --> 12345.68 (Decimal)
//       12345.68 (Single) --> 12345.6787109375 (Double)
//
//       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
//       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
//       67890.13 (Single) --> 67890.12 (Decimal)
//       67890.13 (Single) --> 67890.125 (Double)
//
//       Unable to convert 3.402823E+38 to Int64.
//       Unable to convert 3.402823E+38 to UInt64.
//       Unable to convert 3.402823E+38 to Decimal.
//       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
//       Unable to convert NaN to Int64.
//       Unable to convert NaN to UInt64.
//       Unable to convert NaN to Decimal.
//       NaN (Single) --> NaN (Double)
//
//       Unable to convert Infinity to Int64.
//       Unable to convert Infinity to UInt64.
//       Unable to convert Infinity to Decimal.
//       Infinity (Single) --> Infinity (Double)
//
//       Unable to convert -Infinity to Int64.
//       Unable to convert -Infinity to UInt64.
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Single) --> -Infinity (Double)
// The example displays the following output for conversions performed
// in an unchecked context:
//       -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -3.402823E+38 to Decimal.
//       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
//
//       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
//       -67890.13 (Single) --> -67890.12 (Decimal)
//       -67890.13 (Single) --> -67890.125 (Double)
//
//       -12345.68 (Single) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       -12345.68 (Single) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
//       -12345.68 (Single) --> -12345.68 (Decimal)
//       -12345.68 (Single) --> -12345.6787109375 (Double)
//
//       12345.68 (Single) --> 12345 (0x0000000000003039) (Int64)
//       12345.68 (Single) --> 12345 (0x0000000000003039) (UInt64)
//       12345.68 (Single) --> 12345.68 (Decimal)
//       12345.68 (Single) --> 12345.6787109375 (Double)
//
//       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
//       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
//       67890.13 (Single) --> 67890.12 (Decimal)
//       67890.13 (Single) --> 67890.125 (Double)
//
//       3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert 3.402823E+38 to Decimal.
//       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
//
//       NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       NaN (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert NaN to Decimal.
//       NaN (Single) --> NaN (Double)
//
//       Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert Infinity to Decimal.
//       Infinity (Single) --> Infinity (Double)
//
//       -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Single) --> -Infinity (Double)
Module Example
   Public Sub Main()
      Dim values() As Single = { Single.MinValue, -67890.1234, -12345.6789,
                                 12345.6789, 67890.1234, Single.MaxValue,
                                 Single.NaN, Single.PositiveInfinity,
                                 Single.NegativeInfinity }
      For Each value In values
         Try
             Dim lValue As Long = CLng(value)
             Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                               value, value.GetType().Name,
                               lValue, lValue.GetType().Name)
         Catch e As OverflowException
            Console.WriteLine("Unable to convert {0} to Int64.", value)
         End Try
         Try
             Dim ulValue As UInt64 = CULng(value)
             Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                               value, value.GetType().Name,
                               ulValue, ulValue.GetType().Name)
         Catch e As OverflowException
            Console.WriteLine("Unable to convert {0} to UInt64.", value)
         End Try
         Try
             Dim dValue As Decimal = CDec(value)
             Console.WriteLine("{0} ({1}) --> {2} ({3})",
                               value, value.GetType().Name,
                               dValue, dValue.GetType().Name)
         Catch e As OverflowException
            Console.WriteLine("Unable to convert {0} to Decimal.", value)
         End Try

         Dim dblValue As Double = value
         Console.WriteLine("{0} ({1}) --> {2} ({3})",
                           value, value.GetType().Name,
                           dblValue, dblValue.GetType().Name)
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output for conversions performed
' in a checked context:
'       Unable to convert -3.402823E+38 to Int64.
'       Unable to convert -3.402823E+38 to UInt64.
'       Unable to convert -3.402823E+38 to Decimal.
'       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
'
'       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
'       Unable to convert -67890.13 to UInt64.
'       -67890.13 (Single) --> -67890.12 (Decimal)
'       -67890.13 (Single) --> -67890.125 (Double)
'
'       -12345.68 (Single) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
'       Unable to convert -12345.68 to UInt64.
'       -12345.68 (Single) --> -12345.68 (Decimal)
'       -12345.68 (Single) --> -12345.6787109375 (Double)
'
'       12345.68 (Single) --> 12346 (0x000000000000303A) (Int64)
'       12345.68 (Single) --> 12346 (0x000000000000303A) (UInt64)
'       12345.68 (Single) --> 12345.68 (Decimal)
'       12345.68 (Single) --> 12345.6787109375 (Double)
'
'       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
'       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
'       67890.13 (Single) --> 67890.12 (Decimal)
'       67890.13 (Single) --> 67890.125 (Double)
'
'       Unable to convert 3.402823E+38 to Int64.
'       Unable to convert 3.402823E+38 to UInt64.
'       Unable to convert 3.402823E+38 to Decimal.
'       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
'
'       Unable to convert NaN to Int64.
'       Unable to convert NaN to UInt64.
'       Unable to convert NaN to Decimal.
'       NaN (Single) --> NaN (Double)
'
'       Unable to convert Infinity to Int64.
'       Unable to convert Infinity to UInt64.
'       Unable to convert Infinity to Decimal.
'       Infinity (Single) --> Infinity (Double)
'
'       Unable to convert -Infinity to Int64.
'       Unable to convert -Infinity to UInt64.
'       Unable to convert -Infinity to Decimal.
'       -Infinity (Single) --> -Infinity (Double)
' The example displays the following output for conversions performed
' in an unchecked context:
'       -3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       -3.402823E+38 (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
'       Unable to convert -3.402823E+38 to Decimal.
'       -3.402823E+38 (Single) --> -3.40282346638529E+38 (Double)
'
'       -67890.13 (Single) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
'       -67890.13 (Single) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
'       -67890.13 (Single) --> -67890.12 (Decimal)
'       -67890.13 (Single) --> -67890.125 (Double)
'
'       -12345.68 (Single) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
'       -12345.68 (Single) --> 18446744073709539270 (0xFFFFFFFFFFFFCFC6) (UInt64)
'       -12345.68 (Single) --> -12345.68 (Decimal)
'       -12345.68 (Single) --> -12345.6787109375 (Double)
'
'       12345.68 (Single) --> 12346 (0x000000000000303A) (Int64)
'       12345.68 (Single) --> 12346 (0x000000000000303A) (UInt64)
'       12345.68 (Single) --> 12345.68 (Decimal)
'       12345.68 (Single) --> 12345.6787109375 (Double)
'
'       67890.13 (Single) --> 67890 (0x0000000000010932) (Int64)
'       67890.13 (Single) --> 67890 (0x0000000000010932) (UInt64)
'       67890.13 (Single) --> 67890.12 (Decimal)
'       67890.13 (Single) --> 67890.125 (Double)
'
'       3.402823E+38 (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       3.402823E+38 (Single) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert 3.402823E+38 to Decimal.
'       3.402823E+38 (Single) --> 3.40282346638529E+38 (Double)
'
'       NaN (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       NaN (Single) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert NaN to Decimal.
'       NaN (Single) --> NaN (Double)
'
'       Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       Infinity (Single) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert Infinity to Decimal.
'       Infinity (Single) --> Infinity (Double)
'
'       -Infinity (Single) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       -Infinity (Single) --> 9223372036854775808 (0x8000000000000000) (UInt64)
'       Unable to convert -Infinity to Decimal.
'       -Infinity (Single) --> -Infinity (Double)

如需有關轉換的數字類型的詳細資訊,請參閱.NET Framework 中的類型轉換類型轉換表For more information on the conversion of numeric types, see Type Conversion in the .NET Framework and Type Conversion Tables.

浮點數的功能Floating-point functionality

Single結構和相關的型別提供方法來執行下列作業的類別:The Single structure and related types provide methods to perform the following categories of operations:

  • 值的比較Comparison of values. 您可以呼叫Equals方法,以判斷兩個Single值相等,或CompareTo方法,以判斷兩個值之間的關聯性。You can call the Equals method to determine whether two Single values are equal, or the CompareTo method to determine the relationship between two values.

    Single結構也支援一組完整的比較運算子。The Single structure also supports a complete set of comparison operators. 例如,您可以測試相等或不等,或判斷某個值是否大於或等於另一個值。For example, you can test for equality or inequality, or determine whether one value is greater than or equal to another value. 如果其中一個運算元Double,則Single值轉換成Double之前執行比較。If one of the operands is a Double, the Single value is converted to a Double before performing the comparison. 如果其中一個運算元是整數類資料類型時,它會轉換成Single之前執行比較。If one of the operands is an integral type, it is converted to a Single before performing the comparison. 雖然這些擴展轉換時,它們可能會涉及遺失有效位數。Although these are widening conversions, they may involve a loss of precision.

    警告

    有效位數,因此兩個Single您預期是相等的值可能會變得不相等,這會影響比較的結果。Because of differences in precision, two Single values that you expect to be equal may turn out to be unequal, which affects the result of the comparison. 請參閱測試是否相等如需有關比較兩個區段Single值。See the Testing for equality section for more information about comparing two Single values.

    您也可以呼叫IsNaNIsInfinityIsPositiveInfinity,和IsNegativeInfinity來測試這些特殊值的方法。You can also call the IsNaN, IsInfinity, IsPositiveInfinity, and IsNegativeInfinity methods to test for these special values.

  • 數學運算Mathematical operations. 由語言編譯器和通用中間語言 (CIL) 的指示,而不是依實作常用的算術運算,例如加法、 減法、 乘法和除法Single方法。Common arithmetic operations such as addition, subtraction, multiplication, and division are implemented by language compilers and Common Intermediate Language (CIL) instructions rather than by Single methods. 如果在數學運算的運算元Double,則Single轉換成Double之前執行的作業和作業的結果也是Double值。If the other operand in a mathematical operation is a Double, the Single is converted to a Double before performing the operation, and the result of the operation is also a Double value. 如果另一個運算元是整數類資料類型,它會轉換成Single之前執行的作業和作業的結果也是Single值。If the other operand is an integral type, it is converted to a Single before performing the operation, and the result of the operation is also a Single value.

    您可以執行其他數學運算,藉由呼叫static(Shared Visual Basic 中) 中的方法System.Math類別。You can perform other mathematical operations by calling static (Shared in Visual Basic) methods in the System.Math class. 這些包括常用的算術運算的其他方法 (例如Math.AbsMath.Sign,和Math.Sqrt),幾何 (例如Math.CosMath.Sin),和微積分 (例如Math.Log)。These include additional methods commonly used for arithmetic (such as Math.Abs, Math.Sign, and Math.Sqrt), geometry (such as Math.Cos and Math.Sin), and calculus (such as Math.Log). 在所有情況下,Single值會轉換成DoubleIn all cases, the Single value is converted to a Double.

    您也可以使用操作中的個別位元Single值。You can also manipulate the individual bits in a Single value. BitConverter.GetBytes(Single)方法會傳回其位元模式中的位元組陣列。The BitConverter.GetBytes(Single) method returns its bit pattern in a byte array. 藉由傳遞至該位元組陣列BitConverter.ToInt32方法中,您也可以保留Single值的位元模式中的 32 位元整數。By passing that byte array to the BitConverter.ToInt32 method, you can also preserve the Single value's bit pattern in a 32-bit integer.

  • 捨入Rounding. 捨入通常用於一種技術以減少的差異值的浮點數表示和精確度的問題所造成的影響。Rounding is often used as a technique for reducing the impact of differences between values caused by problems of floating-point representation and precision. 您可以藉由四捨五入Single值,藉由呼叫Math.Round方法。You can round a Single value by calling the Math.Round method. 但請注意,Single值會轉換成Double呼叫方法時,並轉換可能遺失有效位數之前。However, note that the Single value is converted to a Double before the method is called, and the conversion can involve a loss of precision.

  • 格式化Formatting. 您可以將轉換Single值為其字串表示,藉由呼叫ToString方法或使用複合格式化功能。You can convert a Single value to its string representation by calling the ToString method or by using the composite formatting feature. 如需格式字串的浮點值的字串表示的控制方式,請參閱標準數值格式字串自訂數值格式字串主題。For information about how format strings control the string representation of floating-point values, see the Standard Numeric Format Strings and Custom Numeric Format Strings topics.

  • 剖析字串Parsing strings. 您可以將轉換的浮點值的字串表示Single值,藉由呼叫ParseTryParse方法。You can convert the string representation of a floating-point value to a Single value by calling the Parse or TryParse method. 如果剖析作業失敗,Parse方法會擲回例外狀況,而TryParse方法會傳回falseIf the parse operation fails, the Parse method throws an exception, whereas the TryParse method returns false.

  • 類型轉換Type conversion. Single結構提供的明確介面實作IConvertible介面支援任何兩個標準的.NET Framework 資料類型之間轉換。The Single structure provides an explicit interface implementation for the IConvertible interface, which supports conversion between any two standard .NET Framework data types. 語言編譯器也支援以外的所有其他標準數值類型的轉換值的隱含轉換DoubleSingle值。Language compilers also support the implicit conversion of values for all other standard numeric types except for the conversion of Double to Single values. 將值以外的任何標準數值類型的轉換DoubleSingle是擴展轉換,而且不需要使用轉型運算子或轉換方法。Conversion of a value of any standard numeric type other than a Double to a Single is a widening conversion and does not require the use of a casting operator or conversion method.

    不過,轉換的 32 位元和 64 位元的整數值可能遺失有效位數。However, conversion of 32-bit and 64-bit integer values can involve a loss of precision. 下表列出的 32 位元、 64 位元、 有效位數的差異和Double類型:The following table lists the differences in precision for 32-bit, 64-bit, and Double types:

    類型Type 最大有效位數 (小數位數)Maximum precision (in decimal digits) 內部有效位數 (小數位數)Internal precision (in decimal digits)
    Double 1515 1717
    Int32UInt32Int32 and UInt32 1010 1010
    Int64UInt64Int64 and UInt64 1919 1919
    Single 77 99

    有效位數的問題通常會影響Single值轉換成Double值。The problem of precision most frequently affects Single values that are converted to Double values. 在下列範例中,兩個相同的除法運算所產生的值不相等,因為其中一個值是單精確度浮點數值轉換成DoubleIn the following example, two values produced by identical division operations are unequal, because one of the values is a single-precision floating point value that is converted to a Double.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Double value1 = 1/3.0;
          Single sValue2 = 1/3.0f;
          Double value2 = (Double) sValue2;
          Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, 
                                              value1.Equals(value2));
       }
    }
    // The example displays the following output:
    //        0.33333333333333331 = 0.3333333432674408: False
    
    Module Example
       Public Sub Main()
          Dim value1 As Double = 1/3
          Dim sValue2 As Single = 1/3
          Dim value2 As Double = CDbl(sValue2)
          Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2))
       End Sub
    End Module
    ' The example displays the following output:
    '       0.33333333333333331 = 0.3333333432674408: False
    

欄位

Epsilon Epsilon Epsilon Epsilon

代表大於零的最小正 Single 值。Represents the smallest positive Single value that is greater than zero. 這個欄位是常數。This field is constant.

MaxValue MaxValue MaxValue MaxValue

代表 Single 最大的可能值。Represents the largest possible value of Single. 這個欄位是常數。This field is constant.

MinValue MinValue MinValue MinValue

代表 Single 最小的可能值。Represents the smallest possible value of Single. 這個欄位是常數。This field is constant.

NaN NaN NaN NaN

代表非數值 (NaN)。Represents not a number (NaN). 這個欄位是常數。This field is constant.

NegativeInfinity NegativeInfinity NegativeInfinity NegativeInfinity

表示負無限大。Represents negative infinity. 這個欄位是常數。This field is constant.

PositiveInfinity PositiveInfinity PositiveInfinity PositiveInfinity

表示正無限大。Represents positive infinity. 這個欄位是常數。This field is constant.

方法

CompareTo(Object) CompareTo(Object) CompareTo(Object) CompareTo(Object)

比較這個執行個體與特定物件,並且傳回一個整數,指出這個執行個體的值是小於、等於或大於特定物件的值。Compares this instance to a specified object and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object.

CompareTo(Single) CompareTo(Single) CompareTo(Single) CompareTo(Single)

比較這個執行個體與指定的單精確度浮點數,並且傳回整數,這個整數表示這個執行個體的值是小於、等於或大於指定的單精確度浮點數。Compares this instance to a specified single-precision floating-point number and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified single-precision floating-point number.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

傳回值,指出這個執行個體 (Instance) 是否和指定的物件相等。Returns a value indicating whether this instance is equal to a specified object.

Equals(Single) Equals(Single) Equals(Single) Equals(Single)

傳回數值,指示這個執行個體和指定的 Single 物件是否表示相同的值。Returns a value indicating whether this instance and a specified Single object represent the same value.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

GetTypeCode() GetTypeCode() GetTypeCode() GetTypeCode()

傳回實值類型 TypeCodeSingleReturns the TypeCode for value type Single.

IsFinite(Single) IsFinite(Single) IsFinite(Single) IsFinite(Single)
IsInfinity(Single) IsInfinity(Single) IsInfinity(Single) IsInfinity(Single)

傳回值,指出指定的數字是否計算結果為負或正的無限大。Returns a value indicating whether the specified number evaluates to negative or positive infinity.

IsNaN(Single) IsNaN(Single) IsNaN(Single) IsNaN(Single)

傳回值,這個值表示指定的值是否不是數字 (NaN)。Returns a value that indicates whether the specified value is not a number (NaN).

IsNegative(Single) IsNegative(Single) IsNegative(Single) IsNegative(Single)
IsNegativeInfinity(Single) IsNegativeInfinity(Single) IsNegativeInfinity(Single) IsNegativeInfinity(Single)

傳回值,指出指定的數字是否計算結果為負的無限大。Returns a value indicating whether the specified number evaluates to negative infinity.

IsNormal(Single) IsNormal(Single) IsNormal(Single) IsNormal(Single)
IsPositiveInfinity(Single) IsPositiveInfinity(Single) IsPositiveInfinity(Single) IsPositiveInfinity(Single)

傳回值,指出指定數字是否計算結果為正的無限大。Returns a value indicating whether the specified number evaluates to positive infinity.

IsSubnormal(Single) IsSubnormal(Single) IsSubnormal(Single) IsSubnormal(Single)
Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider)

將數字的字串表示 (使用指定樣式和的特定文化特性格式) 轉換為其對等的單精確度浮點數。Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent.

Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider)

將數字的字串表示 (使用指定的特定文化特性格式) 轉換為其對等的單精確度浮點數。Converts the string representation of a number in a specified culture-specific format to its single-precision floating-point number equivalent.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
Parse(String) Parse(String) Parse(String) Parse(String)

將數字的字串表示轉換為其對等的單精確度浮點數。Converts the string representation of a number to its single-precision floating-point number equivalent.

Parse(String, NumberStyles) Parse(String, NumberStyles) Parse(String, NumberStyles) Parse(String, NumberStyles)

將數字的字串表示 (使用指定樣式) 轉換為其對等的單精確度浮點數。Converts the string representation of a number in a specified style to its single-precision floating-point number equivalent.

ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider)

使用指定的格式和特定文化特性格式資訊,將這個執行個體的數值轉換成它的相等字串表示。Converts the numeric value of this instance to its equivalent string representation using the specified format and culture-specific format information.

ToString(String) ToString(String) ToString(String) ToString(String)

使用指定格式,將這個執行個體的數值轉換成它的相等字串表示。Converts the numeric value of this instance to its equivalent string representation, using the specified format.

ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider)

使用指定的特定文化特性格式資訊,將這個執行個體的數值轉換成它的相等字串表示。Converts the numeric value of this instance to its equivalent string representation using the specified culture-specific format information.

ToString() ToString() ToString() ToString()

將這個執行個體的數值轉換為它的相等字串表示。Converts the numeric value of this instance to its equivalent string representation.

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)
TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Single) TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Single) TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Single) TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Single)
TryParse(String, Single) TryParse(String, Single) TryParse(String, Single) TryParse(String, Single)

將數字的字串表示轉換為其對等的單精確度浮點數。Converts the string representation of a number to its single-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(ReadOnlySpan<Char>, Single) TryParse(ReadOnlySpan<Char>, Single) TryParse(ReadOnlySpan<Char>, Single) TryParse(ReadOnlySpan<Char>, Single)
TryParse(String, NumberStyles, IFormatProvider, Single) TryParse(String, NumberStyles, IFormatProvider, Single) TryParse(String, NumberStyles, IFormatProvider, Single) TryParse(String, NumberStyles, IFormatProvider, Single)

將數字的字串表示 (使用指定樣式和的特定文化特性格式) 轉換為其對等的單精確度浮點數。Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

運算子

Equality(Single, Single) Equality(Single, Single) Equality(Single, Single) Equality(Single, Single)

傳回值,這個值表示兩個指定的 Single 值是否相等。Returns a value that indicates whether two specified Single values are equal.

GreaterThan(Single, Single) GreaterThan(Single, Single) GreaterThan(Single, Single) GreaterThan(Single, Single)

傳回值,這個值表示指定的 Single 值是否大於另一個指定的 Single 值。Returns a value that indicates whether a specified Single value is greater than another specified Single value.

GreaterThanOrEqual(Single, Single) GreaterThanOrEqual(Single, Single) GreaterThanOrEqual(Single, Single) GreaterThanOrEqual(Single, Single)

傳回值,這個值表示指定的 Single 值是否大於或等於另一個指定的 Single 值。Returns a value that indicates whether a specified Single value is greater than or equal to another specified Single value.

Inequality(Single, Single) Inequality(Single, Single) Inequality(Single, Single) Inequality(Single, Single)

傳回值,這個值表示兩個指定的 Single 值是否不相等。Returns a value that indicates whether two specified Single values are not equal.

LessThan(Single, Single) LessThan(Single, Single) LessThan(Single, Single) LessThan(Single, Single)

傳回值,這個值表示指定的 Single 值是否小於另一個指定的 Single 值。Returns a value that indicates whether a specified Single value is less than another specified Single value.

LessThanOrEqual(Single, Single) LessThanOrEqual(Single, Single) LessThanOrEqual(Single, Single) LessThanOrEqual(Single, Single)

傳回值,這個值表示指定的 Single 值是否小於或等於另一個指定的 Single 值。Returns a value that indicates whether a specified Single value is less than or equal to another specified Single value.

明確介面實作

IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object)
IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode()
IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider)

如需這個成員的說明,請參閱 ToBoolean(IFormatProvider)For a description of this member, see ToBoolean(IFormatProvider).

IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider)

如需這個成員的說明,請參閱 ToByte(IFormatProvider)For a description of this member, see ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider)

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider)

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider)

如需這個成員的說明,請參閱 ToDecimal(IFormatProvider)For a description of this member, see ToDecimal(IFormatProvider).

IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider)

如需這個成員的說明,請參閱 ToDouble(IFormatProvider)For a description of this member, see ToDouble(IFormatProvider).

IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider)

如需這個成員的說明,請參閱 ToInt16(IFormatProvider)For a description of this member, see ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider)

如需這個成員的說明,請參閱 ToInt32(IFormatProvider)For a description of this member, see ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider)

如需這個成員的說明,請參閱 ToInt64(IFormatProvider)For a description of this member, see ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider)

如需這個成員的說明,請參閱 ToSByte(IFormatProvider)For a description of this member, see ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider)

如需這個成員的說明,請參閱 ToSingle(IFormatProvider)For a description of this member, see ToSingle(IFormatProvider).

IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider)

如需這個成員的說明,請參閱 ToType(Type, IFormatProvider)For a description of this member, see ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt16(IFormatProvider)For a description of this member, see ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt32(IFormatProvider)For a description of this member, see ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt64(IFormatProvider)For a description of this member, see ToUInt64(IFormatProvider).

適用於

執行緒安全性

此型別的所有成員都是安全執行緒。All members of this type are thread safe. 若要修改執行個體狀態會顯示的成員實際上會傳回新的值進行初始化的新執行個體。Members that appear to modify instance state actually return a new instance initialized with the new value. 為與任何其他型別,讀取和寫入共用的變數,其中包含這個型別的執行個體必須受到鎖定,以確保執行緒安全性。As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

另請參閱