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

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 和空结果。


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

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

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

有两种故障模式:如果输入不是有效图像,则 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}");
}
$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}");
$vbLabelText   $csharpLabel

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

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");
$vbLabelText   $csharpLabel

输出

有效的 7 位数字输入(1234567)会生成可扫描的 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
}
$vbLabelText   $csharpLabel

该方法返回空列表而不是 null,因此调用者永远不需要检查返回值是否为 null。 可选的 expectedType 参数按符号体系进行过滤,这样可以防止下游系统在扫描从同一图像中同时获取二维码和 Code 128 时接收到意外的格式。

对于跨多个文件的批量读取,对每个文件应用相同的模式并汇总结果。 ExpectBarcodeTypes 选项在 BarcodeReaderOptions 上预先缩小扫描范围至预期符号体系,从而减少到达验证器的不必要结果。


进一步阅读

-条形码读取教程:扫描配置和读取选项。 -输出数据格式指南:所有 BarcodeResult 属性及其类型。 -从数据创建条形码:每种符号体系的编码约束。

当管道准备就绪投入生产时,请查看许可选项

常见问题解答

什么是条码操作中的空检查?

条码操作中的空检查涉及验证条码结果或输入是否为空,以防止运行时错误并确保条码处理顺利进行。

为什么空检查在C#条码操作中很重要?

空检查对于C#条码操作至关重要,以避免异常并确保应用程序能够优雅处理条码数据可能丢失或无效的情况。

IronBarcode如何帮助空检查?

IronBarcode提供内置方法以轻松处理空检查,使开发人员能够安全地管理条码数据而无需手动实施复杂的验证逻辑。

IronBarcode空检查有什么最佳实践?

最佳实践包括检查条码结果中的空值,在处理之前验证输入,以及使用置信度过滤以确保可靠的条码扫描结果。

IronBarcode可以通过置信度过滤结果以避免空输出吗?

是的,IronBarcode允许通过置信度级别过滤条码结果,有助于减少空输出并确保高精度的条码读取。

IronBarcode是否有办法验证写入输入?

IronBarcode使对写入输入的验证成为可能,以确保编码为条码的数据是正确和完整的,防止条码生成过程中出现问题。

如果未处理空条码结果会发生什么?

如果未处理空条码结果,则可能导致运行时异常,干扰应用程序的流程,可能导致崩溃或错误操作。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 2,121,847 | 版本: 2026.3 刚刚发布
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package BarCode
运行示例 观看您的字符串变成 BarCode。