问题描述
我是C#语言的新手。 C#提供两个类似的接口,名为和进行比较。
在研究它时,我发现IComparable< t>的两种用途。在C#中。
1-对自定义对象集合进行排序
2-重载运算符,如< ,> ,< =,> =等等。
查看我正在使用IComparable< point>的代码。过载<和>运算符。
I'm very new to C# Language. C# provides two similar Interfaces named IComparable Interface and IComparer Interface for comparison.
While working on it, I found two uses of IComparable<t> in C# yet.
1- Sorting custom collections of objects
2- Overloading operators like < , > , <= , >= etc.
have a look at the code where I'm using IComparable<point> to overload < and > operators.
public int CompareTo(Point other)
{
if (this.X > other.X && this.Y > other.Y)
{
return 1;
}
if (this.X < other.X && this.Y < other.Y)
{
return -1;
}
else
{
return 0;
}
}
这是实现此界面的Point类。
This is the Point class which is implementing this interface.
class Point : IComparable<Point>
这里有两个重载的方法<和>运营商。
And in last here the two methods that are overloading < and > Operators.
public static bool operator < (Point p1 , Point p2)
{
return (p1.CompareTo(p2) < 0);
}
public static bool operator >(Point p1, Point p2)
{
return (p1.CompareTo(p2) > 0);
}
除了这些长长的代码和文字外,我的问题很简单。是否有必要始终使用此接口对对象进行排序并重载用于比较等的运算符。
我尝试过的方法:
我在互联网和许多不同的网站上搜索,每个人都在讨论
1-什么是IComparable< t>在C#
或
2-如何使用IComparable< t>在C#
没有人在讨论
>为什么在实时场景中需要这个?我们仍然需要编写额外的代码行来实现这个接口,而不是使用我们为小类编写的自定义方法。
Apart from these long lines of code and text , My question is very simple. Is it necessary to use this interface always to sort the objects and overloading such operators which uses for comparison etc.
What I have tried:
I searched around on internet and on many different websites, everyone is discussing
1- What is IComparable<t> in C#
OR
2- How to use IComparable<t> in C#
Nobody is discussing
> why need this in real time scenarios? still we have to write extra line of code to implementing this interface rather than using our custom methods which simple to write for small classes.
推荐答案
这篇关于为什么总是使用icomparable< T>在C#中比较对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!