官术网_书友最值得收藏!

Implementing the interface

Next, because IComparable has a function, right-click on it, select Quick Actions, and choose Implement interface from the popup. Now, we have to write code.

First, delete throw new NotImplementedException(). Now, we will implement the interface in a way that's sufficient to illustrate the point. For this, enter the following beneath the open curly brace under the public int CompareTo(Quad other) line:

if(this.name.CompareTo(other.name) <0)

Here, this means the current object, and the name of this object is compared to other.name, meaning the other object. Look at where it says (Quad other) in the line above this one; in other words, we're comparing two Quads. So, in the one on the left, this is the one on which the function is being invoked and the other Quad class is the one against which it's being compared. So, if this is less than 0, we will return a number such as -1, else it can return some other value, such as 1. Enter the following between a set of curly braces below this line:

{
return -1;
}
else
{
return 1;
}

We have just implemented CompareTo. Now, notice that the this is not necessary. You can remove it and it will still work. Remember, however, that name essentially means the current object under which CompareTo will be invoked. This is why I like to have the this keyword present, because it is more suggestive of what I want to know.

Basically, what this line is saying is that if the current object when compared to the other name is less than 0, then we return -1, which means that the current object will come before the next object in the list when you sort it. That's a simple interpretation.

主站蜘蛛池模板: 祁阳县| 仁布县| 五河县| 南岸区| 泸溪县| 雅安市| 桂平市| 淅川县| 界首市| 象山县| 无棣县| 五原县| 宁强县| 綦江县| 宁国市| 女性| 裕民县| 阳西县| 钟祥市| 沁源县| 阿勒泰市| 武鸣县| 忻城县| 福安市| 云霄县| 安徽省| 图木舒克市| 吉隆县| 石泉县| 齐齐哈尔市| 都安| 南康市| 汽车| 固始县| 鹿泉市| 成武县| 宁陕县| 临泽县| 平陆县| 长兴县| 安庆市|