728x90
CompareTo
- C#에서 객체 간의 비교를 위해 사용되는 메서드이다.
- 이 메서드는 특정 타입의 두 객체를 비교하여, 그 객체가 다른 객체보다 작거나, 같거나, 큰지를 나타내는 정수 값을 반환한다.
- CompareTo 메서드는 주로 정렬 알고리즘에서 객체들을 정렬하는 데 사용된다.
CompareTo 메서드의 반환값
- 음수 값(’-1’)
- 호출하는 객체가 비교하는 객체보다 작음을 의미한다.
- 0
- 호출하는 객체와 비교하는 객체가 같음을 의미한다.
- 양수 값(’1’)
- 호출하는 객체가 비교하는 객체보다 큼을 의미한다.
사용 예제
- CompareTo 메서드는 주로 IComparable<T> 인터페이스와 함께 사용되며, 기본 데이터 타입과 사용자 정의 클래스에서 사용할 수 있다.
- 기본 데이터 타입
int a = 5; int b = 10; int result = a.CompareTo(b); if (result < 0) { Console.WriteLine("a는 b보다 작습니다."); } else if (result == 0) { Console.WriteLine("a와 b는 같습니다."); } else { Console.WriteLine("a는 b보다 큽니다."); }
- 사용자 정의 클래스
public class Person : IComparable<Person> { public string Name { get; set; } public int Age { get; set; } public int CompareTo(Person other) { if (other == null) return 1; return this.Age.CompareTo(other.Age); } } class Program { static void Main() { Person person1 = new Person { Name = "Alice", Age = 30 }; Person person2 = new Person { Name = "Bob", Age = 25 }; int comparison = person1.CompareTo(person2); if (comparison > 0) { Console.WriteLine($"{person1.Name} is older than {person2.Name}"); } else if (comparison < 0) { Console.WriteLine($"{person1.Name} is younger than {person2.Name}"); } else { Console.WriteLine($"{person1.Name} and {person2.Name} are of the same age"); } } }
728x90
'언어 > C#' 카테고리의 다른 글
Exception has been thrown by the target of an invocation (0) | 2024.08.16 |
---|---|
Protobuf (0) | 2024.08.14 |
MergeFrom (0) | 2024.08.12 |
JsonFormatter.ToDiagnosticString (0) | 2024.08.12 |
ProtoMsg.ProtocolMessageReflection.Descriptor.MessageTypes (0) | 2024.08.12 |