如何在C#中处理条码操作的空检查

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

IronBarcode将扫描结果作为C#中的BarcodeResults集合返回通过BarcodeReader.Read。 如果输入图像无法识别,则此方法返回 null;如果未检测到条形码,则返回空集合。 BarcodeWriter.CreateBarcode如果输入为null、空或格式无效,将抛出异常。

现实世界中的扫描源,例如摄像头画面、文档上传和仓库扫描仪,可能并不总是能提供可读的条形码。 访问结果属性或遍历集合时不检查空值或无效值可能会导致运行时的NullReferenceException。传递无效的字符串给写API可能会导致ArgumentException。 在读取和写入操作中使用保护子句有助于防止生产环境中出现这些异常。

本操作指南解释了如何通过使用保护条款、信任过滤和可重用验证器模式来处理IronBarcode读写操作中的null和空结果。


快速开始:处理条码操作中的空结果

使用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

如何处理条码结果的空和空结果?

存在两种失败模式:如果输入不是有效图像,则BarcodeResults为null,而如果图像不含条形码,则为空。 访问First、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}");
}

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

如何将空安全模式应用于条码写入?

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时,可以防止下游系统接收到意外格式。

对于跨多个文件的批量读取,对每个文件应用相同的模式并汇总结果。 ExpectBarcodeTypes选项在BarcodeReaderOptions上提前缩小扫描到预期符号,因此更少的不需要的结果到达验证器。


进一步阅读

查看许可选项,当管道准备好生产时。

常见问题

在IronBarcode中什么是BarcodeResults,它如何影响空检查?

BarcodeResults是IronBarcode的BarcodeReader.Read方法返回的一个集合。如果输入图像无效,它将为空;如果没有检测到条码,它将为空集合,因此需要适当的空检查以避免运行时异常。

守卫子句如何在IronBarcode操作中防止异常?

守卫子句在读写操作中被应用,以在进行操作之前检查空或无效的输入,从而防止生产中出现NullReferenceException和ArgumentException等异常。

如果您将空或空字符串传递给BarcodeWriter.CreateBarcode会发生什么?

传递空或空字符串给BarcodeWriter.CreateBarcode会立即抛出异常。在调用之前验证输入可以确保避免这些异常,从而维持稳定的编码过程。

ConfidenceThreshold如何影响IronBarcode中的BarcodeReader?

ConfidenceThreshold是BarcodeReaderOptions中的一个属性,用于过滤扫描期间的低质量读取。低于此阈值的读取被丢弃,因此不会到达结果集合,提高了扫描质量。

IronBarcode能否在单次扫描中处理多种条码类型?

是的,IronBarcode可以在单次扫描中处理多种类型。使用具有ExpectBarcodeTypes等设置的BarcodeReaderOptions可以专注于特定符号,有效地管理混合内容的图像。

为什么在下游处理之前验证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。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

阅读更多

准备开始了吗?

NuGet 下载量 2,575,633版本:2026.11刚刚发布