BigInteger.CompareTo Метод
Определение
Сравнивает значение данного экземпляра с другим значением и возвращает целое число, которое показывает, является ли значение данного экземпляра меньшим, большим или равным другому значению.Compares the value of this instance with another value and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the other value.
Перегрузки
CompareTo(UInt64) |
Сравнивает данный экземпляр с 64-разрядным целым числом без знака и возвращает целое число, которое показывает, является ли значение данного экземпляра меньшим или большим по сравнению со значением 64-битового целого числа без знака или равным ему.Compares this instance to an unsigned 64-bit integer and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the unsigned 64-bit integer. |
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(BigInteger) |
Сравнивает данный экземпляр с другим экземпляром BigInteger и возвращает целое число, которое показывает, является ли значение данного экземпляра меньшим, большим или равным значению указанного объекта.Compares this instance to a second BigInteger 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(Int64) |
Сравнивает данный экземпляр с 64-разрядным знаковым целым числом и возвращает целое число, которое показывает, является ли значение данного экземпляра меньшим, большим или равным значению 64-битового знакового целого числа.Compares this instance to a signed 64-bit integer and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the signed 64-bit integer. |
CompareTo(UInt64)
Важно!
Этот API несовместим с CLS.
Сравнивает данный экземпляр с 64-разрядным целым числом без знака и возвращает целое число, которое показывает, является ли значение данного экземпляра меньшим или большим по сравнению со значением 64-битового целого числа без знака или равным ему.Compares this instance to an unsigned 64-bit integer and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the unsigned 64-bit integer.
public:
int CompareTo(System::UInt64 other);
public int CompareTo (ulong other);
[System.CLSCompliant(false)]
public int CompareTo (ulong other);
member this.CompareTo : uint64 -> int
[<System.CLSCompliant(false)>]
member this.CompareTo : uint64 -> int
Public Function CompareTo (other As ULong) As Integer
Параметры
- other
- UInt64
64-разрядное целое число без знака для сравнения.The unsigned 64-bit integer to compare.
Возвращаемое значение
Целое число со знаком, определяющее, как соотносятся между собой данный экземпляр и объект other
. Возможные соотношения показаны в следующей таблице.A signed integer that indicates the relative value of this instance and other
, as shown in the following table.
Возвращаемое значениеReturn value | ОписаниеDescription |
---|---|
Меньше нуляLess than zero | Текущий экземпляр меньше значения параметра other .The current instance is less than other . |
НульZero | Текущий экземпляр равен значению параметра other .The current instance equals other . |
Больше нуляGreater than zero | Текущий экземпляр больше значения параметра other .The current instance is greater than other . |
- Атрибуты
Применяется к
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.
public:
virtual int CompareTo(System::Object ^ obj);
public int CompareTo (object obj);
abstract member CompareTo : obj -> int
override this.CompareTo : obj -> int
Public Function CompareTo (obj As Object) As Integer
Параметры
- obj
- Object
Объект для сравнения.The object to compare.
Возвращаемое значение
Знаковое целое число, определяющее, как соотносятся между собой текущий экземпляр и параметр obj
. Возможные соотношения показаны в следующей таблице.A signed integer that indicates the relationship of the current instance to the obj
parameter, as shown in the following table.
Возвращаемое значениеReturn value | ОписаниеDescription |
---|---|
Меньше нуляLess than zero | Текущий экземпляр меньше значения параметра obj .The current instance is less than obj .
|
НульZero | Текущий экземпляр равен значению параметра obj .The current instance equals obj .
|
Больше нуляGreater than zero | Текущий экземпляр больше значения параметра obj или параметр obj равен null .The current instance is greater than obj , or the obj parameter is null .
|
Реализации
Исключения
obj
не является объектом типа BigInteger.obj
is not a BigInteger.
Примеры
В следующем примере вызывается CompareTo(Object) метод для сравнения BigInteger значения с каждым элементом в массиве объектов:The following example calls the CompareTo(Object) method to compare a BigInteger value with each element in an object array:
object[] values = { BigInteger.Pow(Int64.MaxValue, 10), null,
12.534, Int64.MaxValue, BigInteger.One };
BigInteger number = UInt64.MaxValue;
foreach (object value in values)
{
try {
Console.WriteLine("Comparing {0} with '{1}': {2}", number, value,
number.CompareTo(value));
}
catch (ArgumentException) {
Console.WriteLine("Unable to compare the {0} value {1} with a BigInteger.",
value.GetType().Name, value);
}
}
// The example displays the following output:
// Comparing 18446744073709551615 with '4.4555084156466750133735972424E+189': -1
// Comparing 18446744073709551615 with '': 1
// Unable to compare the Double value 12.534 with a BigInteger.
// Unable to compare the Int64 value 9223372036854775807 with a BigInteger.
// Comparing 18446744073709551615 with '1': 1
Dim values() As Object = { BigInteger.Pow(Int64.MaxValue, 10), Nothing,
12.534, Int64.MaxValue, BigInteger.One }
Dim number As BigInteger = UInt64.MaxValue
For Each value As Object In values
Try
Console.WriteLine("Comparing {0} with '{1}': {2}", number, value,
number.CompareTo(value))
Catch e As ArgumentException
Console.WriteLine("Unable to compare the {0} value {1} with a BigInteger.",
value.GetType().Name, value)
End Try
Next
' The example displays the following output:
' Comparing 18446744073709551615 with '4.4555084156466750133735972424E+189': -1
' Comparing 18446744073709551615 with '': 1
' Unable to compare the Double value 12.534 with a BigInteger.
' Unable to compare the Int64 value 9223372036854775807 with a BigInteger.
' Comparing 18446744073709551615 with '1': 1
Комментарии
Эта перегрузка метода CompareTo реализует метод IComparable.CompareTo .This overload of the CompareTo method implements the IComparable.CompareTo method. Он используется объектами неуниверсальной коллекции для упорядочивания элементов в коллекции.It is used by non-generic collection objects to order the items in the collection.
obj
Параметр должен быть одним из следующих:The obj
parameter must be one of the following:
Объект, тип времени выполнения которого — BigInteger .An object whose run-time type is BigInteger.
ObjectПеременная, значение которой равно
null
.An Object variable whose value isnull
. Если значениеobj
параметра равноnull
, метод возвращает значение 1, указывающее, что текущий экземпляр большеobj
.If the value of theobj
parameter isnull
, the method returns 1, which indicates that the current instance is greater thanobj
.
См. также раздел
Применяется к
CompareTo(BigInteger)
Сравнивает данный экземпляр с другим экземпляром BigInteger и возвращает целое число, которое показывает, является ли значение данного экземпляра меньшим, большим или равным значению указанного объекта.Compares this instance to a second BigInteger 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.
public:
virtual int CompareTo(System::Numerics::BigInteger other);
public int CompareTo (System.Numerics.BigInteger other);
abstract member CompareTo : System.Numerics.BigInteger -> int
override this.CompareTo : System.Numerics.BigInteger -> int
Public Function CompareTo (other As BigInteger) As Integer
Параметры
- other
- BigInteger
Объект для сравнения.The object to compare.
Возвращаемое значение
Знаковое целое число, определяющее, как соотносятся между собой данный экземпляр и объект other
. Возможные соотношения показаны в следующей таблице.A signed integer value that indicates the relationship of this instance to other
, as shown in the following table.
Возвращаемое значениеReturn value | ОписаниеDescription |
---|---|
Меньше нуляLess than zero | Текущий экземпляр меньше значения параметра other .The current instance is less than other .
|
НульZero | Текущий экземпляр равен значению параметра other .The current instance equals other .
|
Больше нуляGreater than zero | Текущий экземпляр больше значения параметра other .The current instance is greater than other .
|
Реализации
Примеры
В следующем примере показано использование CompareTo(BigInteger) метода для упорядочивания списка StarInfo
объектов.The following example illustrates the use of the CompareTo(BigInteger) method to order a list of StarInfo
objects. Каждый StarInfo
объект предоставляет сведения об имени звезды и его расстоянии от земли в милях.Each StarInfo
object provides information about a star's name and its distance from the Earth in miles. StarInfo
реализует IComparable<T> интерфейс, позволяющий StarInfo
Сортировать объекты по универсальным классам коллекций.StarInfo
implements the IComparable<T> interface, which enables StarInfo
objects to be sorted by generic collection classes. Его IComparable<T>.CompareTo реализация просто заключает в оболочку вызов CompareTo(BigInteger) .Its IComparable<T>.CompareTo implementation just wraps a call to CompareTo(BigInteger).
using System;
using System.Collections.Generic;
using System.Numerics;
public struct StarInfo : IComparable<StarInfo>
{
// Define constructors.
public StarInfo(string name, double lightYears)
{
this.Name = name;
// Calculate distance in miles from light years.
this.Distance = (BigInteger) Math.Round(lightYears * 5.88e12);
}
public StarInfo(string name, BigInteger distance)
{
this.Name = name;
this.Distance = distance;
}
// Define public fields.
public string Name;
public BigInteger Distance;
// Display name of star and its distance in parentheses.
public override string ToString()
{
return String.Format("{0,-10} ({1:N0})", this.Name, this.Distance);
}
// Compare StarInfo objects by their distance from Earth.
public int CompareTo(StarInfo other)
{
return this.Distance.CompareTo(other.Distance);
}
}
Imports System.Collections.Generic
Imports System.Numerics
Public Structure StarInfo : Implements IComparable(Of StarInfo)
' Define constructors.
Public Sub New(name As String, lightYears As Double)
Me.Name = name
' Calculate distance in miles from light years.
Me.Distance = CType(Math.Round(lightYears * 5.88e12), BigInteger)
End Sub
Public Sub New(name As String, distance As BigInteger)
Me.Name = name
Me.Distance = distance
End Sub
' Define public fields.
Public Name As String
Public Distance As BigInteger
' Display name of star and its distance in parentheses.
Public Overrides Function ToString() As String
Return String.Format("{0,-10} ({1:N0})", Me.Name, Me.Distance)
End Function
' Compare StarInfo objects by their distance from Earth.
Public Function CompareTo(other As starInfo) As Integer _
Implements IComparable(Of StarInfo).CompareTo
Return Me.Distance.CompareTo(other.Distance)
End Function
End Structure
Затем следующий код создает четыре StarInfo
объекта и сохраняет их в универсальном List<T> объекте.The following code then instantiates four StarInfo
objects and stores them in a generic List<T> object. После List<T>.Sort вызова метода StarInfo
объекты отображаются в порядке их расстояния от земли.After the List<T>.Sort method is called, StarInfo
objects are displayed in order of their distance from the Earth.
public class Example
{
public static void Main()
{
StarInfo star;
List<StarInfo> stars = new List<StarInfo>();
star = new StarInfo("Sirius", 8.6d);
stars.Add(star);
star = new StarInfo("Rigel", 1400d);
stars.Add(star);
star = new StarInfo("Castor", 49d);
stars.Add(star);
star = new StarInfo("Antares", 520d);
stars.Add(star);
stars.Sort();
foreach (StarInfo sortedStar in stars)
Console.WriteLine(sortedStar);
}
}
// The example displays the following output:
// Sirius (50,568,000,000,000)
// Castor (288,120,000,000,000)
// Antares (3,057,600,000,000,000)
// Rigel (8,232,000,000,000,000)
Module Example
Public Sub Main()
Dim star As StarInfo
Dim stars As New List(Of StarInfo)
star = New StarInfo("Sirius", 8.6d)
stars.Add(star)
star = New StarInfo("Rigel", 1400d)
stars.Add(star)
star = New StarInfo("Castor", 49d)
stars.Add(star)
star = New StarInfo("Antares", 520d)
stars.Add(star)
stars.Sort()
For Each star In stars
Console.WriteLine(star)
Next
End Sub
End Module
' The example displays the following output:
' Sirius (50,568,000,000,000)
' Castor (288,120,000,000,000)
' Antares (3,057,600,000,000,000)
' Rigel (8,232,000,000,000,000)
Комментарии
Эта перегрузка метода CompareTo реализует метод IComparable<T>.CompareTo .This overload of the CompareTo method implements the IComparable<T>.CompareTo method. Он используется объектами универсальной коллекции для упорядочивания элементов в коллекции.It is used by generic collection objects to order the items in the collection.
См. также раздел
Применяется к
CompareTo(Int64)
Сравнивает данный экземпляр с 64-разрядным знаковым целым числом и возвращает целое число, которое показывает, является ли значение данного экземпляра меньшим, большим или равным значению 64-битового знакового целого числа.Compares this instance to a signed 64-bit integer and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the signed 64-bit integer.
public:
int CompareTo(long other);
public int CompareTo (long other);
member this.CompareTo : int64 -> int
Public Function CompareTo (other As Long) As Integer
Параметры
- other
- Int64
64-разрядное знаковое целое число для сравнения.The signed 64-bit integer to compare.
Возвращаемое значение
Знаковое целое число, определяющее, как соотносятся между собой данный экземпляр и объект other
. Возможные соотношения показаны в следующей таблице.A signed integer value that indicates the relationship of this instance to other
, as shown in the following table.
Возвращаемое значениеReturn value | ОписаниеDescription |
---|---|
Меньше нуляLess than zero | Текущий экземпляр меньше значения параметра other .The current instance is less than other .
|
НульZero | Текущий экземпляр равен значению параметра other .The current instance equals other .
|
Больше нуляGreater than zero | Текущий экземпляр больше значения параметра other .The current instance is greater than other .
|
Примеры
В следующем примере показан результат вызова метода CompareTo(Int64) с целочисленными значениями.The following example illustrates the result of calling the CompareTo(Int64) method with integral values.
BigInteger bigIntValue = BigInteger.Parse("3221123045552");
byte byteValue = 16;
sbyte sbyteValue = -16;
short shortValue = 1233;
ushort ushortValue = 1233;
int intValue = -12233;
uint uintValue = 12233;
long longValue = 12382222;
ulong ulongValue = 1238222;
Console.WriteLine("Comparing {0} with {1}: {2}",
bigIntValue, byteValue,
bigIntValue.CompareTo(byteValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
bigIntValue, sbyteValue,
bigIntValue.CompareTo(sbyteValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
bigIntValue, shortValue,
bigIntValue.CompareTo(shortValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
bigIntValue, ushortValue,
bigIntValue.CompareTo(ushortValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
bigIntValue, intValue,
bigIntValue.CompareTo(intValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
bigIntValue, uintValue,
bigIntValue.CompareTo(uintValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
bigIntValue, longValue,
bigIntValue.CompareTo(longValue));
Console.WriteLine("Comparing {0} with {1}: {2}",
bigIntValue, ulongValue,
bigIntValue.CompareTo(ulongValue));
// The example displays the following output:
// Comparing 3221123045552 with 16: 1
// Comparing 3221123045552 with -16: 1
// Comparing 3221123045552 with 1233: 1
// Comparing 3221123045552 with 1233: 1
// Comparing 3221123045552 with -12233: 1
// Comparing 3221123045552 with 12233: 1
// Comparing 3221123045552 with 12382222: 1
// Comparing 3221123045552 with 1238222: 1
Dim bigIntValue As BigInteger = BigInteger.Parse("3221123045552")
Dim byteValue As Byte = 16
Dim sbyteValue As SByte = -16
Dim shortValue As Short = 1233
Dim ushortValue As UShort = 1233
Dim intValue As Integer = -12233
Dim uintValue As UInteger = 12233
Dim longValue As Long = 12382222
Dim ulongValue As Integer = 1238222
Console.WriteLine("Comparing {0} with {1}: {2}", _
bigIntValue, byteValue, _
bigIntValue.CompareTo(byteValue))
Console.WriteLine("Comparing {0} with {1}: {2}", _
bigIntValue, sbyteValue, _
bigIntValue.CompareTo(sbyteValue))
Console.WriteLine("Comparing {0} with {1}: {2}", _
bigIntValue, shortValue, _
bigIntValue.CompareTo(shortValue))
Console.WriteLine("Comparing {0} with {1}: {2}", _
bigIntValue, ushortValue, _
bigIntValue.CompareTo(ushortValue))
Console.WriteLine("Comparing {0} with {1}: {2}", _
bigIntValue, intValue, _
bigIntValue.CompareTo(intValue))
Console.WriteLine("Comparing {0} with {1}: {2}", _
bigIntValue, uintValue, _
bigIntValue.CompareTo(uintValue))
Console.WriteLine("Comparing {0} with {1}: {2}", _
bigIntValue, longValue, _
bigIntValue.CompareTo(longValue))
Console.WriteLine("Comparing {0} with {1}: {2}", _
bigIntValue, ulongValue, _
bigIntValue.CompareTo(ulongValue))
' The example displays the following output:
' Comparing 3221123045552 with 16: 1
' Comparing 3221123045552 with -16: 1
' Comparing 3221123045552 with 1233: 1
' Comparing 3221123045552 with 1233: 1
' Comparing 3221123045552 with -12233: 1
' Comparing 3221123045552 with 12233: 1
' Comparing 3221123045552 with 12382222: 1
' Comparing 3221123045552 with 1238222: 1
Комментарии
Если other
является Byte, Int16, Int32, SByte, UInt16или UInt32 , он неявно преобразуется в значение Int64 при вызове метода CompareTo(Int64) .If other
is a Byte, Int16, Int32, SByte, UInt16, or UInt32 value, it is implicitly converted to an Int64 value when the CompareTo(Int64) method is called.