如何在 C# 中處理 BarCode 操作的空值檢查

Curtis Chau
Curtis Chau
已更新: 2026年7月21日

IronBarcode 透過 BarcodeReader.Read 在 C# 中以 BarcodeResults 集合返回掃描結果。 如果輸入影像無法識別,則此方法傳回 null;如果未偵測到條碼,則傳回空集合。 BarcodeWriter.CreateBarcode 如果輸入為 null、空的或格式無效,則會拋出異常。

現實世界中的掃描來源,例如攝影機畫面、文件上傳和倉庫掃描儀,可能無法總是提供可讀的條碼。 在迴圈集合或訪問結果屬性之前,若未檢查 null 或空值可能在運行時導致 NullReferenceException。傳遞無效字串給寫 API 可能會導致 ArgumentException。 在讀取和寫入操作中使用保護子句有助於防止生產環境中出現這些異常。

本操作指南說明了如何在IronBarcode的讀寫操作中通過使用防範子句、信任度篩選和可重用驗證器模式來處理空和空結果。


快速入門:處理BarCode操作中的空結果

請使用 IronBarcode 的保護模式以安全檢查 BarcodeResults 集合,然後再訪問任何結果屬性。 立即閱讀並查看以下簡要內容,開始學習:

  1. 1使用 IronBarcode 安裝 NuGet Package Manager

    PM > Install-Package BarCode

  2. 2複製並運行這段程式碼。

    using IronBarCode;
    using System;
    using System.Linq;
    
    BarcodeResults results = BarcodeReader.Read("label.png");
    
    // Guard: null or empty
    if (results is null || results.Count == 0)
    {
        Console.WriteLine("No barcodes detected.");
        return;
    }
    
    Console.WriteLine(results.First().Value);
  3. 3部署到您的生產環境進行測試

    立即在您的項目中開始使用 IronBarcode,並使用 免費試用
    arrow pointer

如何處理空值與空的BarCode結果?

有兩種失敗模式:如果輸入為無效圖像,則 BarcodeResults 為 null;如果圖像中不包含條碼,則為空。 在未驗證兩個條件的情況下訪問 First、Value 或進行迴圈會導致運行時異常。

進入處理循環前,請檢查以下兩個條件:

輸入

一個 Code128 條碼發貨標籤 (成功路徑) 和一個不包含任何條碼的空白圖像 (失敗路徑)。

編碼 SHP-20240001 的 Code128 條碼,用作出貨標籤的輸入

shipping-label.png (success path)

沒有條碼的空白白色影像,用於觸發空結果路徑

blank-image.png (failure path, no barcode present)

using IronBarCode;

// BarcodeReader.Read() returns a BarcodeResults collection, not a single result
BarcodeResults results = BarcodeReader.Read("shipping-label.png");

// Null check: image was not recognized as a valid image source
// Empty check: image was valid but contained no detectable barcodes
if (results is null || results.Count == 0)
{
    // Log, return a default, or throw a domain-specific exception
    Console.WriteLine("No barcodes found in the input image.");
    return;
}

// Collection is safe to iterate; each BarcodeResult holds one decoded barcode
foreach (BarcodeResult result in results)
{
    // Guard individual result properties; partial scans or severely
    // damaged barcodes can produce results where .Value is empty or whitespace
    if (string.IsNullOrWhiteSpace(result.Value))
    {
        Console.WriteLine($"Empty value detected for {result.BarcodeType}");
        continue;
    }

    // BarcodeType identifies the symbology (Code128, QRCode, EAN8, etc.)
    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
}

每一個 BarcodeResult 提供 Value 和 Text 字符串屬性,均返回解碼的條碼內容。 條碼嚴重損壞或掃描不完整可能會產生空白值或空格值。 在每個結果上使用 string.IsNullOrWhiteSpace 可防止空值進入下游系統。

BarcodeReaderOptions 還有一個 ConfidenceThreshold 屬性 (0.0 至 1.0),在低質量讀取結果進入結果集合前刪除它們:

using IronBarCode;

// ConfidenceThreshold filters low-quality reads before they enter the
// BarcodeResults collection. Reads below the threshold are discarded
// during scanning, not after, so no post-filtering of the collection is needed.
var options = new BarcodeReaderOptions
{
    ConfidenceThreshold = 0.7  // range 0.0 to 1.0; lower values accept weaker signals
};

BarcodeResults results = BarcodeReader.Read("shipping-label.png", options);

// Still check for null and empty even with a threshold applied;
// an image with no barcodes returns an empty collection, not null
if (results is null || results.Count == 0)
{
    Console.WriteLine("No barcodes met the confidence threshold.");
    return;
}

foreach (var result in results)
    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");

如何將空安全模式應用於BarCode寫入?

BarcodeWriter.CreateBarcode 接受字符串值以及 BarcodeWriterEncoding 或 BarcodeEncoding 枚舉。 傳遞 null 值或空字串會立即拋出異常。 格式限制也適用:EAN-8 接受 7 到 8 個數字位,UPC-A 接受 11 到 12 個,Code 128 有字符限制。 在呼叫之前驗證輸入可以避免這些異常情況進入編碼步驟:

using IronBarCode;

// Input may arrive from user input, a database, or an API response
string inputValue = GetValueFromUserOrDatabase(); // Could be null

// Guard: null, empty, or whitespace input cannot produce a valid barcode
if (string.IsNullOrWhiteSpace(inputValue))
{
    Console.WriteLine("Cannot generate barcode: input value is null or empty.");
    return;
}

// Guard: format-specific constraints must be satisfied before encoding
// EAN-8 accepts exactly 7 or 8 numeric digits (the 8th is the check digit)
BarcodeWriterEncoding encoding = BarcodeWriterEncoding.EAN8;
if (encoding == BarcodeWriterEncoding.EAN8 && !System.Text.RegularExpressions.Regex.IsMatch(inputValue, @"^\d{7,8}$"))
{
    Console.WriteLine("EAN-8 requires exactly 7 or 8 numeric digits.");
    return;
}

// Input is validated; CreateBarcode will not throw for null or format mismatch
GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);
barcode.SaveAsPng("output-barcode.png");

輸出

有效的 7 位數字輸入 (1234567) 產生可掃描的 EAN-8 條碼。 空值、空值或非數字輸入會被保護子句捕獲,永遠不會到達編碼步驟。

根據有效的7位輸入碼1234567產生的EAN-8條碼

寫入 API 也會進行內部驗證:它會檢查校驗和、驗證長度限制,並拒絕所選編碼的無效字元。 上述的保護條款可以及早發現問題,使呼叫者能夠控制錯誤訊息和恢復路徑。 有關支持的編碼及其限制的完整列表,請參見 條碼創建操作指南 和 從數據創建條碼指南。


如何在後續處理前驗證結果?

當條碼資料匯入到另一個系統(資料庫寫入、API 呼叫、標籤印表機)時,最好在傳遞資料之前,將結果計數、值完整性和類型檢查整合到一個可重複使用的方法中:

輸入

作為驗證器讀取目標使用於倉庫掃描的 Code128 條碼。

Code128 條碼編碼 WH-SCAN-4471 用作驗證器範例中的倉庫掃描輸入
using IronBarCode;
using System.Collections.Generic;
using System.Linq;

// Reusable validation helper — consolidates null, empty, value, and
// expected-format checks into a single method. Returns an empty list
// (never null) so callers do not need to null-check the return value.
public static class BarcodeValidator
{
    public static List<BarcodeResult> GetValidResults(
        string imagePath,
        BarcodeEncoding? expectedType = null,
        double confidenceThreshold = 0.7)
    {
        // Apply confidence threshold at scan level via BarcodeReaderOptions
        var options = new BarcodeReaderOptions
        {
            ConfidenceThreshold = confidenceThreshold
        };

        BarcodeResults results = BarcodeReader.Read(imagePath, options);

        // Return empty list instead of null so callers never need to null-check the return value
        if (results is null || results.Count == 0)
            return new List<BarcodeResult>();

        return results
            .Where(r => !string.IsNullOrWhiteSpace(r.Value))           // skip results with empty decoded data
            .Where(r => expectedType == null || r.BarcodeType == expectedType) // null accepts any symbology
            .ToList();
    }
}

// Usage: pass the image path and the symbology you expect
var validated = BarcodeValidator.GetValidResults(
    "warehouse-scan.png",
    expectedType: BarcodeEncoding.Code128,
    confidenceThreshold: 0.7);

if (validated.Count == 0)
{
    // No valid results; log the failure and skip downstream processing
    return;
}

// All results have passed null, empty, type, and confidence checks
foreach (var barcode in validated)
{
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()); // placeholder for your downstream call
}

此方法傳回空列表而不是 null,因此呼叫者永遠不需要檢查傳回值是否為 null。 選擇性 expectedType 參數根據符號篩選,避免當掃描同一圖像中檢測到 QR 代碼和 Code 128 時,將意外格式傳遞給下游系統。

對跨多個文件的批量讀取,請對每個文件應用相同的模式並彙總結果。 BarcodeReaderOptions 上的 ExpectBarcodeTypes 選項預先將掃描縮小至預期符號,因此更少無用結果進入驗證器。


延伸閱讀

查看授權選項當管道準備好投入生產時。

常見問題

IronBarcode中BarcodeResults是什麼,它如何影響空值檢查?

BarcodeResults是IronBarcode的BarcodeReader.Read方法返回的一個集合。如果輸入圖片無效,它將為空值;如果未檢測到條碼,則為空,這需要適當的空值檢查以避免運行時異常。

防護條款如何防止IronBarcode操作中的異常?

防護條款應用於讀取和寫入操作中,在繼續操作之前檢查空值或無效輸入,防止像NullReferenceException和ArgumentException這樣的異常在生產中發生。

如果您將空值或空字串傳遞給BarcodeWriter.CreateBarcode會怎麼樣?

將空值或空字串傳遞給BarcodeWriter.CreateBarcode會立即引發異常。在調用之前進行輸入驗證可以確保避免這些異常,維持穩定的編碼過程。

ConfidenceThreshold如何影響IronBarcode中的BarcodeReader?

ConfidenceThreshold是BarcodeReaderOptions中的一個屬性,它在掃描期間過濾掉低質量的讀數。低於此門檻的讀數會被丟棄,因此它們不會進入結果集合,從而提高掃描質量。

IronBarcode能否在單次掃描中處理多種條碼類型?

是的,IronBarcode能夠在一次掃描中處理多種類型。使用BarcodeReaderOptions搭配ExpectBarcodeTypes等設置,可以專注於特定符號學,有效管理混合內容圖片。

為什麼在下游處理之前驗證BarcodeResults很重要?

驗證BarcodeResults以確保結果數量、值的完整性和類型一致性可以防止不正確的資料影響資料庫寫入、API呼叫和其他系統交互。

不檢查IronBarcode操作中的空結果會有什麼影響?

不檢查空結果可能會在掃描操作中導致NullReferenceExceptions,因為訪問不存在的BarcodeResult屬性將會失敗。

IronBarcode的可重用驗證器模式如何運作?

IronBarcode的可重用驗證器模式將空值檢查、空檢查、值完整性和預期格式驗證整合到單一方法中,簡化了在結果下游使用之前的驗證過程。

BarcodeWriterEncoding在條碼創建期間處理的約束有哪些?

BarcodeWriterEncoding根據條碼類型施加如字串長度和字符有效性的約束。例如,EAN-8必須有7或8個數位。正確格式化的輸入避免了編碼過程中的異常。

IronBarcode如何確保已掃描條碼的質量?

IronBarcode使用BarcodeReaderOptions中的ConfidenceThreshold等屬性確保只有高品質條碼被包含在結果中。這種預掃描過濾意味著低品質讀數在進一步處理之前被捨棄。

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

閱讀更多

準備好開始了嗎?

NuGet 下載次數 2,575,633版本:2026.11剛剛發布