And*_*ber 15
CompareTo()告诉你哪一个,或者一个是否大于/小于另一个,而Equals()只是告诉你它们是否是等价的.
如果您只想知道"它们是否是相同的值",则使用Equals().如果您还需要知道他们如何比较,请使用CompareTo()
int a = 50;
int b = 10;
//if you need to know if they are equal:
if(a.Equals(b)){
//won't execute
}
//this would check if they are equal, as well
if(a.CompareTo(b) == 0){
//won't execute
}
//if you need to know if a is bigger than b, specifically:
if(a.CompareTo(b) > 0){
//will execute
}
//this would check to see if a is less than b
if(a.CompareTo(b) < 0){
//won't execute
}
Run Code Online (Sandbox Code Playgroud)
最后,请注意,对于原始类型,并不严格需要这些Equals()和CompareTo()方法int,因为标准比较运算符已经过载,因此您可以执行以下操作:
//this would check if they are equal, as well
if(a == b){
//won't execute
}
//if you need to know if a is bigger than b, specifically:
if(a > b){
//will execute
}
//this would check to see if a is less than b
if(a < b){
//won't execute
}
Run Code Online (Sandbox Code Playgroud)
最后,你string在问题中提到过.Equals()并CompareTo()按照我的描述工作string.请记住,CompareTo()对字符串执行的"比较" 基于字母排序,因此"abcdefg" < "z"
Equals 将返回一个布尔值来表示相等。
CompareTo将返回一个 int,“小于”为 -1(或任何其他负值),“等于”为 0,“大于”为 1(或任何其他正值)。这种方法对于排序算法很有用。
功能CompareTo实际上是功能的超集Equals.一个CompareTo功能使然排序,前,后或等于而Equals功能仅仅规定平等.因此,它实际上可以定义Equals来讲CompareTo
public bool Equals(string other) {
return 0 == CompareTo(other);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40337 次 |
| 最近记录: |