Single.Equals Single.Equals Single.Equals Single.Equals Method

定义

返回一个值,该值指示 Single 的两个实例是否表示同一个值。Returns a value indicating whether two instances of Single represent the same value.

重载

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

返回一个值,该值指示此实例是否等于指定的对象。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.

Equals(Object) Equals(Object) Equals(Object) 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 Object Object 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和除以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定义其范围接近于零的正值的最小表达式,因此差异的边距必须Epsilon大于。Because 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参数和 a 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)它们调用方法,如果Singleobj参数不false是值,则总是返回。Otherwise, 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 中的DoubleDecimal以外Double的所有基元数值类型C#,第一个比较返回true ,因为编译器会自动执行扩大转换和调用Equals(Single)方法,而第二次比较返回falseEquals(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.Single.Equals#2] [!code-vbSystem.Single.Equals#2][!code-csharpSystem.Single.Equals#2] [!code-vbSystem.Single.Equals#2]

另请参阅

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.

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 Single Single 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和除以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定义其范围接近于零的正值的最小表达式,因此差异的边距必须Epsilon大于。Because 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. 因此,建议您不要在比较Epsilon Double值是否相等时使用。Because 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,因为Epsilon当使用的Single值为零时,是可表示的最小值。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,这两个值Double是前面的代码示例Equals(Single)中找到的方法不相等的两个值。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参数和 a 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)它们调用方法,如果Singleobj参数不false是值,则总是返回。Otherwise, 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 中的DoubleDecimal以外Double的所有基元数值类型C#,第一个比较返回true ,因为编译器会自动执行扩大转换和调用Equals(Single)方法,而第二次比较返回falseEquals(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.Single.Equals#2] [!code-vbSystem.Single.Equals#2][!code-csharpSystem.Single.Equals#2] [!code-vbSystem.Single.Equals#2]

另请参阅

适用于