簡體   English   中英

Windows Phone 8.1比較Control.Content給出錯誤的結果

[英]Windows Phone 8.1 comparing Control.Content giving wrong result

我遇到了一個很奇怪的問題,我有以下代碼:

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語句中比較它們時,它們都給出false? 我在其中檢查字符串是否為空或null的其他語句的值為true。

您正在執行引用相等比較,而不是值相等比較。 您的代碼等同於以下內容:

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)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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM