考慮以下幾點:爲對象陣列中平等字符串比較:意想不到假
using System;
namespace ObjectArrayWeirdness
{
public class Program
{
public static object[] Change(object[] set)
{
object[] result = new object[set.Length];
// If the following two lines are replaced with:
// result[0] = "ab";
// then ArrayEquals will evaluate true.
result[0] = "a";
result[0] += "b";
return result;
}
public static bool ArrayEquals(object[] a, object[] b)
{
if (a.Length != b.Length) return false;
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i])
{
return false;
}
}
return true;
}
static void Main(string[] args)
{
object[] expected = { "ab" };
object[] actual = Change(new object[] { 1 });
Console.WriteLine(ArrayEquals(expected, actual));
}
}
}
輸出:
輸出result[0].GetType()
的
false
:
System.String
我的問題:
是否在
ArrayEquals
比較失敗,因爲它是比較對象引用,而不是價值?如果是這樣的話,爲什麼在正確的字符串被分配到一個步驟(不使用
+=
)到result[0]
時成功?
我必須承認我預期的正常字符串比較鑑於GetType()
標識都a[0]
和b[0]
爲字符串。
非常感謝! – 2015-04-04 00:24:26