Single.Equals 方法

定義

傳回數值,指示 Single 的兩個執行個體是否表示相同的值。Returns a value indicating whether two instances of Single represent the same value.

多載

Equals(Object)

傳回值,指出此執行個體是否等於指定的物件。Returns a value indicating whether this instance is equal to a specified object.

Equals(Single)

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

Equals(Object)

傳回值,指出此執行個體是否等於指定的物件。Returns a value indicating whether this instance is equal to a specified object.

public:
 override bool Equals(System::Object ^ obj);
public override bool Equals (object obj);
override this.Equals : obj -> bool
Public Overrides Function Equals (obj As Object) As Boolean

參數

obj
Object

要與這個執行個體比較的物件。An object to compare with this instance.

傳回

如果 trueobj 的執行個體,並且等於這個執行個體的值,則為 Single,否則為 falsetrue if obj is an instance of Single and equals the value of this instance; otherwise, false.

範例

下列程式碼範例示範 Equals 方法。The following code example demonstrates the Equals method.

obj1 = (Single)500;

if ( a.Equals( obj1 ) )
{
   Console::WriteLine( "The value type and reference type values are equal." );
}
obj1 = (Single)500;
if (a.Equals(obj1)) {
    Console.WriteLine("The value type and reference type values are equal.");
}
Obj1 = CType(500, Single)

If A.Equals(Obj1) Then
    Console.WriteLine("The value type and reference type values are equal.")
End If

備註

Equals 方法應該謹慎使用,因為兩個明顯的相等值可能會因為兩個值的不同精確度而不相等。The Equals method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. 下列範例會報告 Single 值3333和除以 1 x 3 所傳回的 Single 不相等。The following example reports that the Single value .3333 and the Single returned by dividing 1 by 3 are unequal.

// Initialize two floats with apparently identical values
float float1 = .33333f;
object float2 = 1/3;
// Compare them for equality
Console.WriteLine(float1.Equals(float2));    // displays false
' Initialize two singles with apparently identical values
Dim single1 As Single = .33333
Dim single2 As Object = 1/3
' Compare them for equality
Console.WriteLine(single1.Equals(single2))    ' displays False

其中一個建議的技巧是定義兩個值之間的差異可接受邊界(例如其中一個值的 .01%),而不是比較是否相等。Rather than comparing for equality, one recommended technique involves defining an acceptable margin of difference between two values (such as .01% of one of the values). 如果兩個值之間差異的絕對值小於或等於該邊界,則差異可能是因為有效位數的差異,因此值可能會是相等的。If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be due to differences in precision and, therefore, the values are likely to be equal. 下列範例會使用這項技術來比較33333和1/3,上述程式碼範例發現的兩個 Single 值不相等。The following example uses this technique to compare .33333 and 1/3, the two Single values that the previous code example found to be unequal.

// Initialize two floats with apparently identical values
float float1 = .33333f;
object float2 = (float) 1/3;
// Define the tolerance for variation in their values
float difference = Math.Abs(float1 * .0001f);

// Compare the values
// The output to the console indicates that the two values are equal
if (Math.Abs(float1 - (float) float2) <= difference)
   Console.WriteLine("float1 and float2 are equal.");
else
   Console.WriteLine("float1 and float2 are unequal.");
' Initialize two singles with apparently identical values
Dim single1 As Single = .33333
Dim single2 As Object = 1/3
' Define the tolerance for variation in their values
Dim difference As Single = Math.Abs(single1 * .0001f)

' Compare the values
' The output to the console indicates that the two values are equal
If Math.Abs(single1 - CSng(single2)) <= difference Then
   Console.WriteLine("single1 and single2 are equal.")
Else
   Console.WriteLine("single1 and single2 are unequal.")
End If

在此情況下,這些值是相等的。In this case, the values are equal.

注意

因為 Epsilon 會定義其範圍接近零之正值的最小運算式,所以差異的邊界必須大於 EpsilonBecause Epsilon defines the minimum expression of a positive value whose range is near zero, the margin of difference must be greater than Epsilon. 通常,它會比 Epsilon多倍。Typically, it is many times greater than Epsilon.

超出記載精確度的浮點數精確度,是 .NET Framework 的實值和版本所特有。The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of the .NET Framework. 因此,兩個特定數位的比較可能會在 .NET Framework 版本之間變更,因為數位的內部標記法的精確度可能會改變。Consequently, a comparison of two particular numbers might change between versions of the .NET Framework because the precision of the numbers' internal representation might change.

給呼叫者的注意事項

編譯器多載解析可能會考慮兩個 Equals(Object) 方法多載的行為明顯差異。Compiler overload resolution may account for an apparent difference in the behavior of the two Equals(Object) method overloads. 如果 obj 引數與 Single 之間的隱含轉換已定義,而引數未輸入為 Object,則編譯器可能會執行隱含轉換,並呼叫 Equals(Single) 方法。If an implicit conversion between the obj argument and a Single is defined and the argument is not typed as an Object, compilers may perform an implicit conversion and call the Equals(Single) method. 否則,它們會呼叫 Equals(Object) 方法,如果其 obj 引數不是 Single 值,則一律會傳回 falseOtherwise, they call the Equals(Object) method, which always returns false if its obj argument is not a Single value. 下列範例說明兩個方法多載之間的行為差異。The following example illustrates the difference in behavior between the two method overloads. 在所有基本數數值型別的情況下,除了 Visual Basic 中的 Double,以及中C#的 DecimalDouble 以外,第一個比較會傳回 true,因為編譯器會自動執行擴輾轉換並呼叫 Equals(Single) 方法,而第二個比較會傳回 false,因為編譯器會呼叫 Equals(Object) 方法。In the case of all primitive numeric types except for Double in Visual Basic and except for Decimal and Double in C#, the first comparison returns true because the compiler automatically performs a widening conversion and calls the Equals(Single) method, whereas the second comparison returns false because the compiler calls the Equals(Object) method.

[! code-csharpsystem.web. Equals # 2][! code-vbsystem.web. Equals # 2][!code-csharpSystem.Single.Equals#2] [!code-vbSystem.Single.Equals#2]

另請參閱

Equals(Single)

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

public:
 virtual bool Equals(float obj);
public bool Equals (float obj);
override this.Equals : single -> bool
Public Function Equals (obj As Single) As Boolean

參數

obj
Single

要與這個執行個體比較的物件。An object to compare with this instance.

傳回

如果 true 等於這個執行個體則為 obj,否則為 falsetrue if obj is equal to this instance; otherwise, false.

實作

備註

這個方法會實作用 System.IEquatable<T> 介面,而且執行效果稍微優於 Equals,因為它不需要將 obj 參數轉換成物件。This method implements the System.IEquatable<T> interface, and performs slightly better than Equals because it does not have to convert the obj parameter to an object.

擴展轉換Widening Conversions

視您的程式設計語言而定,可能會將 Equals 方法編碼,其中參數類型的位較少(較窄),而不是實例類型。Depending on your programming language, it might be possible to code an Equals method where the parameter type has fewer bits (is narrower) than the instance type. 這是可行的,因為有些程式設計語言會執行隱含的擴輾轉換,將參數表示為具有與實例多個位的類型。This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance.

例如,假設實例類型為 Single,且參數類型為 Int32For example, suppose the instance type is Single and the parameter type is Int32. Microsoft C#編譯器會產生指示,以 Single 物件的形式來表示參數的值,然後產生 Single.Equals(Single) 方法,以比較實例的值和參數的加寬標記法。The Microsoft C# compiler generates instructions to represent the value of the parameter as a Single object, and then generates a Single.Equals(Single) method that compares the values of the instance and the widened representation of the parameter.

請參閱程式設計語言的檔,以判斷其編譯器是否執行數數值型別的隱含擴輾轉換。Consult your programming language's documentation to determine if its compiler performs implicit widening conversions of numeric types. 如需詳細資訊,請參閱類型轉換表主題。For more information, see the Type Conversion Tables topic.

比較的有效位數Precision in Comparisons

請小心使用 Equals 方法,因為兩個值的精確度不同,因此兩個明顯相等的值可能不相等。The Equals method should be used with caution, because two apparently equivalent values can be unequal because of the differing precision of the two values. 下列範例會報告 Single 值3333和除以 1 x 3 所傳回的 Single 不相等。The following example reports that the Single value .3333 and the Single returned by dividing 1 by 3 are unequal.

// Initialize two floats with apparently identical values
float float1 = .33333f;
float float2 = 1/3;
// Compare them for equality
Console.WriteLine(float1.Equals(float2));    // displays false
' Initialize two singles with apparently identical values
Dim single1 As Single = .33333
Dim single2 As Single = 1/3
' Compare them for equality
Console.WriteLine(single1.Equals(single2))    ' displays False

有一項比較技巧可以避免與比較相等相關的問題,包括定義兩個值之間的可接受邊界(例如其中一個值的 .01%)。One comparison technique that avoids the problems associated with comparing for equality involves defining an acceptable margin of difference between two values (such as .01% of one of the values). 如果兩個值之間差異的絕對值小於或等於該邊界,則差異可能會是有效位數差異的結果,因此值可能相等,因此。If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be an outcome of differences in precision and, therefore, the values are likely to be equal. 下列範例會使用這項技術來比較33333和1/3,這是前一個程式碼範例所發現的兩個 Single 值是不相等的。The following example uses this technique to compare .33333 and 1/3, which are the two Single values that the previous code example found to be unequal.

// Initialize two floats with apparently identical values
float float1 = .33333f;
float float2 = (float) 1/3;
// Define the tolerance for variation in their values
float difference = Math.Abs(float1 * .0001f);

// Compare the values
// The output to the console indicates that the two values are equal
if (Math.Abs(float1 - float2) <= difference)
   Console.WriteLine("float1 and float2 are equal.");
else
   Console.WriteLine("float1 and float2 are unequal.");
' Initialize two singles with apparently identical values
Dim single1 As Single = .33333
Dim single2 As Single = 1/3
' Define the tolerance for variation in their values
Dim difference As Single = Math.Abs(single1 * .0001f)

' Compare the values
' The output to the console indicates that the two values are equal
If Math.Abs(single1 - single2) <= difference Then
   Console.WriteLine("single1 and single2 are equal.")
Else
   Console.WriteLine("single1 and single2 are unequal.")
End If

在此情況下,這些值是相等的。In this case, the values are equal.

注意

因為 Epsilon 會定義其範圍接近零之正值的最小運算式,所以差異的邊界必須大於 EpsilonBecause Epsilon defines the minimum expression of a positive value whose range is near zero, the margin of difference must be greater than Epsilon. 通常,它會比 Epsilon多倍。Typically, it is many times greater than Epsilon. 因此,我們建議您在比較 Double 值是否相等時,不要使用 EpsilonBecause of this, we recommend that you do not use Epsilon when comparing Double values for equality.

另一個避免與相等比較相關的問題的方法,就是比較兩個浮點數與某個絕對值之間的差異。A second technique that avoids the problems associated with comparing for equality involves comparing the difference between two floating-point numbers with some absolute value. 如果差異小於或等於該絕對值,則數位相等。If the difference is less than or equal to that absolute value, the numbers are equal. 如果大於此值,則數位不相等。If it is greater, the numbers are not equal. 其中一種方法是任意選取絕對值。One way to do this is to arbitrarily select an absolute value. 不過,這會造成問題,因為可接受的差異邊界取決於 Single 值的大小。However, this is problematic, because an acceptable margin of difference depends on the magnitude of the Single values. 第二種方式會利用浮點格式的設計功能:兩個浮點值的整數表示中的尾陣列件之間的差異表示可能的浮點值數目,以分隔兩個值。A second way takes advantage of a design feature of the floating-point format: The difference between the mantissa components in the integer representations of two floating-point values indicates the number of possible floating-point values that separates the two values. 例如,0.0 和 Epsilon 之間的差異是1,因為在使用值為零的 Single 時,Epsilon 是最小的可顯示值。For example, the difference between 0.0 and Epsilon is 1, because Epsilon is the smallest representable value when working with a Single whose value is zero. 下列範例會使用這項技術來比較33333和1/3,這是前一個程式碼範例中,Equals(Single) 方法所找到的兩個 Double 值是不相等的。The following example uses this technique to compare .33333 and 1/3, which are the two Double values that the previous code example with the Equals(Single) method found to be unequal. 請注意,此範例會使用 BitConverter.GetBytesBitConverter.ToInt32 方法,將單精確度浮點值轉換為其整數表示。Note that the example uses the BitConverter.GetBytes and BitConverter.ToInt32 methods to convert a single-precision floating-point value to its integer representation.

using System;

public class Example
{
   public static void Main()
   {
      float value1 = .1f * 10f;
      float value2 = 0f;
      for (int ctr = 0; ctr < 10; ctr++)
         value2 += .1f;
         
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2,
                        HasMinimalDifference(value1, value2, 1));
   }

   public static bool HasMinimalDifference(float value1, float value2, int units)
   {
      byte[] bytes = BitConverter.GetBytes(value1);
      int iValue1 = BitConverter.ToInt32(bytes, 0);
      
      bytes = BitConverter.GetBytes(value2);
      int iValue2 = BitConverter.ToInt32(bytes, 0);
      
      // If the signs are different, return false except for +0 and -0.
      if ((iValue1 >> 31) != (iValue2 >> 31))
      {
         if (value1 == value2)
            return true;
          
         return false;
      }

      int diff = Math.Abs(iValue1 - iValue2);

      if (diff <= units)
         return true;

      return false;
   }
}
// The example displays the following output:
//        1 = 1.00000012: True
Module Example
   Public Sub Main()
      Dim value1 As Single = .1 * 10
      Dim value2 As Single = 0
      For ctr As Integer =  0 To 9
         value2 += CSng(.1)
      Next
               
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2,
                        HasMinimalDifference(value1, value2, 1))
   End Sub

   Public Function HasMinimalDifference(value1 As Single, value2 As Single, units As Integer) As Boolean
      Dim bytes() As Byte = BitConverter.GetBytes(value1)
      Dim iValue1 As Integer =  BitConverter.ToInt32(bytes, 0)
      
      bytes = BitConverter.GetBytes(value2)
      Dim iValue2 As Integer =  BitConverter.ToInt32(bytes, 0)
      
      ' If the signs are different, Return False except for +0 and -0.
      If ((iValue1 >> 31) <> (iValue2 >> 31)) Then
         If value1 = value2 Then
            Return True
         End If           
         Return False
      End If

      Dim diff As Integer =  Math.Abs(iValue1 - iValue2)

      If diff <= units Then
         Return True
      End If

      Return False
   End Function
End Module
' The example displays the following output:
'       1 = 1.00000012: True

超出記載精確度的浮點數精確度,是 .NET Framework 的實值和版本所特有。The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of the .NET Framework. 因此,兩個數字的比較可能會產生不同的結果,這取決於 .NET Framework 的版本,因為數位的內部標記法的精確度可能會改變。Consequently, a comparison of two numbers might produce different results depending on the version of the .NET Framework, because the precision of the numbers' internal representation might change.

給呼叫者的注意事項

編譯器多載解析可能會考慮兩個 Equals(Object) 方法多載的行為明顯差異。Compiler overload resolution may account for an apparent difference in the behavior of the two Equals(Object) method overloads. 如果 obj 引數與 Single 之間的隱含轉換已定義,而引數未輸入為 Object,則編譯器可能會執行隱含轉換,並呼叫 Equals(Single) 方法。If an implicit conversion between the obj argument and a Single is defined and the argument is not typed as an Object, compilers may perform an implicit conversion and call the Equals(Single) method. 否則,它們會呼叫 Equals(Object) 方法,如果其 obj 引數不是 Single 值,則一律會傳回 falseOtherwise, they call the Equals(Object) method, which always returns false if its obj argument is not a Single value. 下列範例說明兩個方法多載之間的行為差異。The following example illustrates the difference in behavior between the two method overloads. 在所有基本數數值型別的情況下,除了 Visual Basic 中的 Double,以及中C#的 DecimalDouble 以外,第一個比較會傳回 true,因為編譯器會自動執行擴輾轉換並呼叫 Equals(Single) 方法,而第二個比較會傳回 false,因為編譯器會呼叫 Equals(Object) 方法。In the case of all primitive numeric types except for Double in Visual Basic and except for Decimal and Double in C#, the first comparison returns true because the compiler automatically performs a widening conversion and calls the Equals(Single) method, whereas the second comparison returns false because the compiler calls the Equals(Object) method.

[! code-csharpsystem.web. Equals # 2][! code-vbsystem.web. Equals # 2][!code-csharpSystem.Single.Equals#2] [!code-vbSystem.Single.Equals#2]

另請參閱

適用於