Зачем переопределять методы ToString(), GetHashCode(), Equals() - C#
Формулировка задачи:
В голове не укладывается. Зачем это на практике нужно?
Решение задачи: «Зачем переопределять методы ToString(), GetHashCode(), Equals()»
textual
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication2
- {
- class Program
- {
- static void Main(string[] args)
- {
- Point p1 = new Point(10, 10);
- Point p2 = new Point(10, 10);
- Console.WriteLine("ToString(): {0}",p1.ToString());
- Console.WriteLine("Equals(): {0}",p1.Equals(p2));
- Console.ReadLine();
- }
- }
- public class Point
- {
- public int X { get; set; }
- public int Y { get; set; }
- public Point() { }
- public Point(int xPos, int yPos)
- {
- X = xPos; Y = yPos;
- }
- public override string ToString()
- {
- return string.Format("X = {0}; Y = {1}", X, Y);
- }
- public override bool Equals(object obj)
- {
- if (obj is Point)
- {
- if (this.X == ((Point)obj).X &&
- this.Y == ((Point)obj).Y)
- return true;
- else
- return false;
- }
- return false;
- }
- public override int GetHashCode()
- {
- return this.ToString().GetHashCode();
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д