我知道它返回整数,但我需要知道基于什么。
例子:
string s1 = "world";
string s2 = "World";
Console.WriteLine(string.Compare(s1,s2));
Console.WriteLine(s1.CompareTo(s2));
它为两者返回
-1
。但是,如果我们在 w
中大写 s1
并在 s2
中小写 w 它返回 1
.
所以需要一些解释。
当一个(或两个字符串)是null
时,我们可以看到
difference:
string s1 = null;
string s2 = "World";
// -1, since null < "World"
Console.WriteLine(string.Compare(s1,s2));
// exception thrown, attempt to call null.CompareTo("World")
Console.WriteLine(s1.CompareTo(s2));
如果我们谈论的是行为,那么它们是相同的,并且在引擎盖下都调用相同的
static int string.Compare
,默认为StringComparison.CurrentCulture
.
主要区别在于
static method
vs instance method
。所以s1.CompareTo(s2)
如果s1为空则抛出NullReferenceException
。