关于Icomparable interfece [英] About Icomparable interfece
问题描述
请帮我描述一下这段代码。
Please help me describe this code.
public int CompareTo(object obj)
{
if (obj is Person)
{
Person otherPerson = obj as Person;
return this.Age - otherPerson.Age;
}
else
{
throw new ArgumentException(
"Object to compare to is not a Person object.");
}
}
特别是我感兴趣。这两行创建的是什么?
in particular i intresting.What this two lines created for?
Person otherPerson = obj as Person;
return this.Age - otherPerson.Age;
推荐答案
// input obj cast to Person
Person otherPerson = obj as Person;
// return the difference of Age values of both comparing objects
return this.Age - otherPerson.Age;
阅读 IComparable Interface [ ^ ] CompareTo方法应该根据比较返回整数值,如果年龄值相等,这两个对象被认为是在同一位置。
Read the documentation of IComparable Interface[^] CompareTo method should return integer value based on the comparison, here two objects are consider as in same position if the age values are equal.
as
运算符检查给定对象,如果可以将其转换为给定类型,则将其作为该类型返回。否则,它返回null
。当您不知道将哪种类型的值传递给方法(通常是事件处理程序)并且您需要检查以便通过尝试将其用作不是的类型时不会导致问题时使用它:
例如:
Theas
operator checks the given object and if it can be converted to the given type returns it as that type. Otherwise, it returnsnull
. It's used when you don't know what type of value is being passed into a method (often an event handler) and you need to check so that you don't cause problems by trying to use it as a type it isn't:
For example:
ListBox lb = new ListBox();
...
Control c = lb;
...
TextBox tb = c as TextBox;
将提供 tb / code> ; as< code> null
因为ListBox无法转换为文本框,而
will give tb/code> as <code>null
becasue a ListBox cannot be converted into a Textbox, whereas
TextBox tb = new TextBox();
...
Control c = tb;
...
TextBox tb2 = c as TextBox;
将tb2作为TextBox实例。
这是一种检查类型的安全方法,如果无法进行转换,则可能导致类型转换异常。
第二行减去两个属性(或字段)值,并将结果返回给调用方法。
will give tb2 as a TextBox instance.
It's a safe way of checking the type without potentially causing a type casting exception if the conversion cannot be made.
The second line subtracts two property (or field) values and returns the result to the calling method.
这篇关于关于Icomparable interfece的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!