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

This article was translated from English: Does it need improvement?
Translated
View the article in English

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

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

本文說明如何使用 guard 子句、置信度過濾和可重複使用的驗證器模式來處理IronBarcode讀取和寫入操作中的 null 和空結果。


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

使用 IronBarcode 的 guard 模式,在存取任何結果屬性之前安全地檢查 BarcodeResults 集合。 立即閱讀並查看以下簡要內容,開始學習:

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/BarCode

    PM > Install-Package BarCode
  2. 複製並運行這段程式碼。

    using IronBarCode;
    
    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. 部署到您的生產環境進行測試

    今天就在您的專案中開始使用免費試用IronBarcode

    arrow pointer

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

有兩種故障模式:如果輸入不是有效影像,則 BarcodeResults 為 null;如果影像不包含條碼,則為空。 存取 Value,或在未驗證兩個條件的情況下進行迭代,將導致運行時異常。

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

輸入

Code128 條碼運輸標籤(成功路徑)和不包含條碼的空白影像(失敗路徑)。

Code128 barcode encoding SHP-20240001 used as the shipping label input

shipping-label.png(成功路徑)

Blank white image with no barcode used to trigger the empty result path

blank-image.png(失敗路徑,無條碼)

:path=/static-assets/barcode/content-code-examples/how-to/null-checking/null-guard.cs
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}");
}
Imports IronBarCode

' BarcodeReader.Read() returns a BarcodeResults collection, not a single result
Dim results As BarcodeResults = 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 Nothing OrElse results.Count = 0 Then
    ' Log, return a default, or throw a domain-specific exception
    Console.WriteLine("No barcodes found in the input image.")
    Return
End If

' Collection is safe to iterate; each BarcodeResult holds one decoded barcode
For Each result As BarcodeResult 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) Then
        Console.WriteLine($"Empty value detected for {result.BarcodeType}")
        Continue For
    End If

    ' BarcodeType identifies the symbology (Code128, QRCode, EAN8, etc.)
    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")
Next
$vbLabelText   $csharpLabel

每個 BarcodeResult 都提供 ValueText 字串屬性,這兩個屬性都傳回解碼後的條碼內容。 條碼嚴重損壞或掃描不完整可能會產生空白值或空格值。 在每個結果上使用 string.IsNullOrWhiteSpace 以防止空值到達下游系統。

BarcodeReaderOptions 還有一個 ConfidenceThreshold 屬性(0.0 到 1.0),用於在低品質讀取到達結果集合之前將其丟棄:

:path=/static-assets/barcode/content-code-examples/how-to/null-checking/confidence-filter.cs
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}");
Imports 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.
Dim options As New BarcodeReaderOptions With {
    .ConfidenceThreshold = 0.7  ' range 0.0 to 1.0; lower values accept weaker signals
}

Dim results As BarcodeResults = 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 Nothing OrElse results.Count = 0 Then
    Console.WriteLine("No barcodes met the confidence threshold.")
    Return
End If

For Each result In results
    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")
Next
$vbLabelText   $csharpLabel

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

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

:path=/static-assets/barcode/content-code-examples/how-to/null-checking/null-safe-write.cs
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");
Imports IronBarCode

' Input may arrive from user input, a database, or an API response
Dim inputValue As String = GetValueFromUserOrDatabase() ' Could be Nothing

' Guard: null, empty, or whitespace input cannot produce a valid barcode
If String.IsNullOrWhiteSpace(inputValue) Then
    Console.WriteLine("Cannot generate barcode: input value is null or empty.")
    Return
End If

' Guard: format-specific constraints must be satisfied before encoding
' EAN-8 accepts exactly 7 or 8 numeric digits (the 8th is the check digit)
Dim encoding As BarcodeWriterEncoding = BarcodeWriterEncoding.EAN8
If encoding = BarcodeWriterEncoding.EAN8 AndAlso Not System.Text.RegularExpressions.Regex.IsMatch(inputValue, "^\d{7,8}$") Then
    Console.WriteLine("EAN-8 requires exactly 7 or 8 numeric digits.")
    Return
End If

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

輸出

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

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

寫入 API 也會進行內部驗證:它會檢查校驗和、驗證長度限制,並拒絕所選編碼的無效字元。 上述的保護條款可以及早發現問題,使呼叫者能夠控制錯誤訊息和恢復路徑。 有關支援的編碼格式及其限制的完整清單,請參閱BarCode建立教學"從資料建立BarCode"指南


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

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

輸入

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

Code128 條碼編碼 WH-SCAN-4471 用作驗證器範例中的倉庫掃描輸入
:path=/static-assets/barcode/content-code-examples/how-to/null-checking/barcode-validator.cs
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
}
Imports IronBarCode
Imports System.Collections.Generic
Imports 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 Module BarcodeValidator
    Public Function GetValidResults(
        imagePath As String,
        Optional expectedType As BarcodeEncoding? = Nothing,
        Optional confidenceThreshold As Double = 0.7) As List(Of BarcodeResult)

        ' Apply confidence threshold at scan level via BarcodeReaderOptions
        Dim options As New BarcodeReaderOptions With {
            .ConfidenceThreshold = confidenceThreshold
        }

        Dim results As BarcodeResults = BarcodeReader.Read(imagePath, options)

        ' Return empty list instead of null so callers never need to null-check the return value
        If results Is Nothing OrElse results.Count = 0 Then
            Return New List(Of BarcodeResult)()
        End If

        Return results _
            .Where(Function(r) Not String.IsNullOrWhiteSpace(r.Value)) _          ' skip results with empty decoded data
            .Where(Function(r) expectedType Is Nothing OrElse r.BarcodeType = expectedType) _ ' null accepts any symbology
            .ToList()
    End Function
End Module

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

If validated.Count = 0 Then
    ' No valid results; log the failure and skip downstream processing
    Return
End If

' All results have passed null, empty, type, and confidence checks
For Each barcode In validated
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()) ' placeholder for your downstream call
Next barcode
$vbLabelText   $csharpLabel

此方法傳回空列表而不是 null,因此呼叫者永遠不需要檢查傳回值是否為 null。 可選的 expectedType 參數按符號體系進行過濾,這樣可以防止下游系統在掃描從同一圖像中同時獲取二維碼和 Code 128 時接收到意外的格式。

對於跨多個檔案的批次讀取,對每個檔案套用相同的模式並彙總結果。 ExpectBarcodeTypes 選項在 BarcodeReaderOptions 上預先縮小掃描範圍至預期符號體系,從而減少到達驗證器的不必要結果。


延伸閱讀

-條碼讀取教學:掃描配置和讀取選項。 -輸出資料格式指南:所有 BarcodeResult 屬性及其類型。 -從資料建立條碼:每種符號體系的編碼約束。

當管道準備好投入生產時,請查看許可證選項

常見問題解答

BarCode 操作中的 null 檢查是什麼?

BarCode操作中的空值檢查,是指驗證BarCode結果或輸入是否為空值,以防止執行時錯誤並確保BarCode處理順暢。

為何在 C# BARCODE 操作中,空值檢查如此重要?

在 C# BarCode 操作中,空值檢查至關重要,藉此可避免發生例外狀況,並確保應用程式能妥善處理 BarCode 資料缺失或無效的情況。

IronBarcode 如何協助進行空值檢查?

IronBarcode 提供內建方法,可輕鬆處理 null 檢查,讓開發人員無需手動實作複雜的驗證邏輯,即可安全地管理 BarCode 資料。

在 IronBarcode 中進行 null 檢查有哪些最佳實踐?

最佳實務包括檢查 BarCodeResults 是否為 null 值、在處理前驗證輸入資料,以及使用信心度篩選器來確保可靠的 BarCode 掃描結果。

IronBarcode 能否根據信心度篩選結果,以避免出現空結果?

是的,IronBarcode 支援根據信心等級篩選 BarCode 結果,有助於減少無效輸出,並確保 BarCode 讀取的高準確性。

是否有方法能使用 IronBarcode 驗證手寫輸入?

IronBarcode 能對寫入的輸入資料進行驗證,確保編碼至 BarCode 的資料正確且完整,從而避免 BarCode 生成過程中的問題。

若未處理 null BarCode 結果會發生什麼情況?

若未處理BarCode結果為空的情況,可能會導致執行時異常並中斷應用程式流程,進而引發潛在的當機或操作錯誤。

Curtis Chau
技術作家

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

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 2,143,620 | 版本: 2026.4 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。