簡體   English   中英

C#-布爾值和if語句

[英]C# - boolean and if statement

我目前正在使用Visual Studios上的Google API Vision編寫代碼來分析圖像。 但是我在循環期間發生了一個問題。 分析返回注釋列表(汽車,車輛,陸地車輛等),我想用“ if”過濾它,所以我這樣寫:

var image = Google.Cloud.Vision.V1.Image.FromFile("C:\\temp\\sequence\\1.jpg");
var client = ImageAnnotatorClient.Create();
var response = client.DetectLabels(image);
CropHintsAnnotation confidence = client.DetectCropHints(image);
bool empty = false;

foreach (var annotation in response)
{
    textBox1.Text += annotation.Description + "\r\n";
    textBox1.Text += "Score : " + annotation.Score + "\r\n";
    if (annotation.Description.Equals("vehicle"))
    {
        empty = false;
    }
    else
    {
        empty = true;
    }

}
textBox1.Text += "\r\nEmpty ?       " + empty + "\r\n\r\n";

因此,如果我寫得不錯,它應該說“ Empty?false”,因為分析一次返回了“車輛”。 我也嘗試替換了:

annotation.Description.Equals("vehicle")

通過

annotation.Description.Contains("vehicle") == true

但是沒有辦法,它仍然說“ Empty?true”,因為它不應該這樣。

有任何想法嗎 ?

在此先感謝您閱讀本文檔以及獲得幫助!

不完全確定您要在此處執行的操作,但是假設response有多個項目,則empty變量將僅代表最后一個項目的值。

原因是,對於循環的每次迭代, if到達if語句,它將進入該循環,否則將進入else循環,並且肯定會進入兩者之一,因此對於每次迭代,將分配empty值並覆蓋先前的值

至於代碼本身,用這種方式編寫代碼更整潔:

empty = !annotation.Description.Equals("vehicle");

您應該更改的是將分配的行移動到循環中:

foreach(/*...*/)
{
    /*...*/
    empty = !annotation.Description.Equals("vehicle");
    textBox1.Text += "\r\nEmpty ?       " + empty + "\r\n\r\n";
}

您是否考慮過返回字符串的大小寫? 嘗試忽略這種情況:

annotation.Description.Equals("vehicle", StringComparison.InvariantCultureIgnoreCase)

附帶說明: Equals函數返回Boolean ,因此您可以刪除整個if語句並將代碼簡化為:

empty = !annotation.Description.Equals("vehicle", StringComparison.InvariantCultureIgnoreCase)

可能性很小:

  1. 您可以檢查車輛的順序嗎,也可能是它確實確實在索引0上找到了車輛的描述,但索引1不是車輛,因此它覆蓋了先前的值。 在這種情況下,您可能希望在滿足所需條件時跳出循環。

     foreach (var annotation in response) { // not sure if you want this to textBox1.Text += annotation.Description + "\\r\\n"; textBox1.Text += "Score : " + annotation.Score + "\\r\\n"; if (annotation.Description.Equals("vehicle", StringComparison.InvariantCultureIgnoreCase)) { empty = false; textBox1.Text += "\\r\\nEmpty ? " + empty + "\\r\\n\\r\\n"; //possibly also break if you've achieved what you want. break; } } 

暫無
暫無

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

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