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

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

IronBarcode透過BarcodeResults集合在C#中返回掃描結果。 如果輸入圖像未被識別,則此方法返回空值;如果未檢測到條碼,則返回空集合。 BarcodeWriter.CreateBarcode拋出例外,如果輸入為空、為null或格式無效。

現實世界中的掃描來源,如攝像頭餵入、文件上傳和倉庫掃描儀,可能不會總是提供可讀的條碼。 在未檢查空值或未檢查為空的情況下存取結果屬性或迭代集合,可能會在運行時導致ArgumentException。 在讀寫操作中使用保護子句有助於防止這些例外在生產中出現。

這份操作指南解釋如何在IronBarcode的讀寫操作中,通過使用保護子句、自信過濾和可重複使用的驗證器範式來處理空值和空結果。


快速開始:在條碼操作中處理空結果

使用IronBarcode的保護模式在存取任何結果屬性之前安全地檢查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

如何處理空和空條碼結果?

有兩種失敗模式:BarcodeResults為空,如果輸入不是一個有效的圖像;而如果圖像中不包含條碼,則為空。 在未驗證兩條件下存取Value或迭代會導致運行時例外。

在進入處理迴圈之前檢查這兩個條件:

輸入

Code128條碼運送標籤(成功路徑)和一個不含條碼的空圖像(失敗路徑)。

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

shipping-label.png(成功路徑)

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

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

每個Text字串屬性,兩者都返回解碼的條碼內容。 嚴重損壞的條碼或部分掃描可能會產生空值或空白值。 對每個結果使用string.IsNullOrWhiteSpace以防止空值進入下游系統。

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

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

BarcodeEncoding枚舉。 傳遞空字串或空字串會立即拋出。 格式限制也適用: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位數字輸入(EAN-8條碼。 空、空或非數字輸入會被保護子句捕獲,永遠不會進入編碼步驟。

從有效的7位數字輸入1234567生成的EAN-8條碼

寫入API也進行自己的內部驗證:它檢查校驗和、驗證長度限制,並拒絕無效字元以選定編碼。 上述保護子句提早捕獲問題,讓呼叫者能夠控制錯誤訊息和恢復路徑。 如需完整的支援編碼和其限制列表,請參見條碼建立操作指南從資料建立條碼指南


如何在下游處理前驗證結果?

當條碼資料進入另一個系統(資料庫寫入、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

該方法返回空列表而不是空值,因此呼叫者不需要對返回值進行空值檢查。 可選的Code 128時接收到意外格式。

對多個文件進行批量閱讀,對每個文件應用相同的模式並聚合結果。 BarcodeReaderOptions上事先將掃描限制在預期符號上,因此較少的非預期結果到達驗證器。


進一步閱讀

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

常見問題

什麼是條碼操作中的空值檢查?

條碼操作中的空值檢查涉及驗證條碼結果或輸入為空,以防止運行時錯誤並確保順利的條碼處理。

為什麼在C#條碼操作中空值檢查很重要?

空值檢查在C#條碼操作中至關重要,以避免異常並確保應用程式能够優雅地處理條碼資料可能遺失或無效的情況。

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

IronBarcode提供了內建的方法來輕鬆處理空值檢查,使開發人員能够安全地管理條碼資料,而不需手動完成複雜的驗證邏輯。

IronBarcode的空值檢查有哪些最佳實踐?

最佳實踐包括檢查BarcodeResults的空值,處理前驗證輸入,以及使用信心篩選以確保可靠的條碼掃描結果。

IronBarcode能通過信心水平篩選來避免空輸出嗎?

是的,IronBarcode允許依據信心水平篩選條碼結果,這有助於減少空輸出並確保條碼讀取的高準確性。

IronBarcode是否有辦法驗證寫入輸入?

IronBarcode允許驗證寫入輸入以確保被編入條碼的資料正確且完整,防止條碼生成時的問題。

如果不處理空條碼結果會發生什麼情況?

如果不處理空條碼結果,可能會導致運行時異常並破壞應用程式的流程,造成潛在的崩潰或錯誤操作。

IronBarcode如何幫助改善業務流程效率?

IronBarcode通過使條碼生成和讀取快速且準確來提高業務流程效率,減少手動資料輸入錯誤,並改善庫存和資產追蹤。

將IronBarcode實現於專案中需要什麼程式設計技能?

基本的C#程式設計知識足以將IronBarcode實現於專案中,因為它提供了簡單的方法和全面的文件來指導開發者。

IronBarcode適合於小型專案和大型企業應用嗎?

IronBarcode設計為可擴展且多功能,使其適合小型專案和需要強大條碼解決方案的大型企業應用。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備好開始了嗎?
Nuget 下載 2,317,217 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動嗎?

想快速驗證嗎? PM > Install-Package BarCode
運行範例觀看您的字串成為條碼。