Windows Phone 8.1比较Control.Content给出了错误的结果

时间:2016-03-31 22:42:45

标签: c# windows-phone boolean compare

我遇到了一个非常奇怪的问题,我有以下代码:

for (int i = 0; i < Board.Length - 2; i++)
{
    var a = Board[i].Content;
    var b = Board[i + 1].Content;
    var c = Board[i + 2].Content;
    if (a == b && a == c &&
        (string) a != string.Empty && a != null)
    {
        MessageDialog msd = new MessageDialog("test");
        await msd.ShowAsync();
    }
}

其中Board是按钮数组,a,b,c具有相同的值“1”。但是当在if语句中比较它们时,它们都是假的?我检查字符串是空还是空的其他语句给出值true。

1 个答案:

答案 0 :(得分:1)

您正在执行引用相等性比较而不是值相等性比较。您的代码与以下内容相同:

for (int i = 0; i < Board.Length - 2; i++)
{
    object a = Board[i].Content;
    object b = Board[i + 1].Content;
    object c = Board[i + 2].Content;
    if (a == b && a == c &&
        (string) a != string.Empty && a != null)
    {
        MessageDialog msd = new MessageDialog("test");
        await msd.ShowAsync();
    }
}

这意味着a == b被解析为<object> == <object>而不是<string> == <string>,这导致与Object.ReferenceEquals(a, b)等效的比较。要获得价值平等,您应立即投放abc。现在a是一个字符串,您也可以使用String.IsNullOrEmpty而不是手动检查两者:

for (int i = 0; i < Board.Length - 2; i++)
{
    string a = (string)Board[i].Content;
    string b = (string)Board[i + 1].Content;
    string c = (string)Board[i + 2].Content;
    if (a == b && a == c && !String.IsNullOrEmpty(a))
    {
        MessageDialog msd = new MessageDialog("test");
        await msd.ShowAsync();
    }
}
相关问题