![](/img/trans.png)
[英]Wrong behavior and Catastrophic Failure with ListBox control - Windows Phone 8.1
[英]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)
。 為了獲得價值平等,您應該立即轉換a
, b
和c
。 現在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.