IRONSOFTWAREHOME

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

Curtis Chau
Curtis Chau
Updated: 2026年5月9日

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

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

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


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

使用IronBarcode的保護模式在存取任何結果屬性之前安全地檢查BarcodeResults集合。 立即使用此最小讀取和檢查開始:

  1. 1Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode

  2. 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);
    C#
  3. 3部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronBarcode,透過免費試用
    arrow pointer

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

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

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

輸入

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

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

shipping-label.png(成功路徑)

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

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

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}");
}

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

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}");

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

BarcodeEncoding枚舉。 傳遞空字串或空字串會立即拋出。 格式限制也適用: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位數字輸入(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
}

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

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


進一步閱讀

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

常見問題

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

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

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

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

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

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

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

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

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

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

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

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

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

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

How does IronBarcode's reusable validator pattern work?

IronBarcode's reusable validator pattern consolidates null checks, empty checks, value integrity, and expected format validation into a single method, simplifying the validation process before results are used downstream.

What are some constraints that BarcodeWriterEncoding handles during barcode creation?

BarcodeWriterEncoding imposes constraints like string length and character validity based on the barcode type. For example, EAN-8 must have 7 or 8 numeric digits. Correctly formatted input avoids exceptions during encoding.

How does IronBarcode ensure the quality of scanned barcodes?

IronBarcode uses properties such as ConfidenceThreshold in BarcodeReaderOptions to ensure only high-quality barcodes are included in results. This pre-scanning filter means low-quality reads are discarded before further processing.

Curtis Chau
技術作家

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

...
閱讀更多

準備好開始了嗎?

Nuget Downloads 2,422,100版本:2026.9剛剛發布

立即獲取您的免費30天試用金鑰
不需要信用卡或帳戶建立
C# NuGet程式庫,用於PDF
通過NuGet安裝

版本: 2026.9

PM > Install-Package BarCode
nuget.org/packages/BarCode/
  1. 在解決方案資源管理器中,右鍵點擊References,管理NuGet包
  2. 選擇瀏覽並搜尋"IronBarCode"
  3. 選擇包並安裝
C# PDF DLL
下載DLL

版本: 2026.9

  1. 下載並解壓IronBarCode至您的Solution目錄中的~/Libs等位置
  2. 在Visual Studio解決方案資源管理器中右鍵點擊References,選擇瀏覽,"IronBarCode.dll"

$999起的授權費用

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費即時演示
Booking Badge

全球數百萬工程師信賴

Iron Software的客戶標誌
獲取您的無義務諮詢
完成下方表單或發送電子郵件至sales@ironsoftware.com
您的詳細資訊將始終保密。
全球數百萬工程師信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立