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

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

BarcodeReader.Read()返回的是一个BarcodeResults集合,而不是单个值。 如果输入图像无法识别,集合可能为空;如果没有检测到条码,集合将是空的。 在写入方面,当传入空或无效输入时,BarcodeWriter.CreateBarcode()将抛出异常。 在代码触及结果属性或生成输出之前,两个路径都需要保护子句。

本指南涵盖对IronBarcode读写操作的空和空结果处理——防止ArgumentException进入生产的防御模式。

快速入门:处理条码操作中的空结果

在访问任何结果属性之前,保护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,它是BarcodeResult对象的集合。 需防范两种故障模式:集合本身为空(输入未识别为有效图像),以及集合为空(有效图像,但未找到条码)。 在未检查这两个条件的情况下访问.Value或进行迭代会导致运行时异常。

标准保护模式检查这两个条件后再进入处理循环:

using IronBarCode;

BarcodeResults results = BarcodeReader.Read("shipping-label.png");

// Null check: image may not be recognized
// Empty check: image recognized but no barcodes found
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;
}

foreach (BarcodeResult result in results)
{
    // Guard individual result properties
    if (string.IsNullOrWhiteSpace(result.Value))
    {
        Console.WriteLine($"Empty value detected for {result.BarcodeType}");
        continue;
    }

    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
}
using IronBarCode;

BarcodeResults results = BarcodeReader.Read("shipping-label.png");

// Null check: image may not be recognized
// Empty check: image recognized but no barcodes found
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;
}

foreach (BarcodeResult result in results)
{
    // Guard individual result properties
    if (string.IsNullOrWhiteSpace(result.Value))
    {
        Console.WriteLine($"Empty value detected for {result.BarcodeType}");
        continue;
    }

    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
}
$vbLabelText   $csharpLabel

每个.Text —— 两者都返回解码后的条码内容。 在正常操作中这些属性是填充的,但存在边缘情况:严重损坏的条码、部分扫描或低信任度检测可能会产生结果值为空或空格的情况。 在个别结果上检查string.IsNullOrWhiteSpace()可以在数据传播前捕捉到这些情况。

属性.Confidence(一个0.0到1.0之间的双精度数)提供了额外的质量信号。 对于生产系统,我们可以将空检查与信任度阈值结合起来:

double minimumConfidence = 0.7;

var validResults = results
    .Where(r => !string.IsNullOrWhiteSpace(r.Value) && r.Confidence >= minimumConfidence)
    .ToList();

if (validResults.Count == 0)
{
    Console.WriteLine("No barcodes met the confidence threshold.");
    return;
}
double minimumConfidence = 0.7;

var validResults = results
    .Where(r => !string.IsNullOrWhiteSpace(r.Value) && r.Confidence >= minimumConfidence)
    .ToList();

if (validResults.Count == 0)
{
    Console.WriteLine("No barcodes met the confidence threshold.");
    return;
}
$vbLabelText   $csharpLabel

MinimumConfidence属性,该属性在扫描级别而不是后处理中进行过滤。 在选项对象中设置这一点对于大批量批量扫描场景来说更为清晰。

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

BarcodeWriter.CreateBarcode()接受一个字符串值以及一个BarcodeWriterEncodingBarcodeEncoding枚举。 传递一个空或空字符串将抛出异常。 此外,应用特定格式的约束—— EAN-8要求恰好有7-8个数字,UPC-A要求11-12位数字,Code 128有最大字符限制。 违反这些约束也会导致抛出异常。

防御模式在调用CreateBarcode()前验证输入。

using IronBarCode;

string inputValue = GetValueFromUserOrDatabase(); // Could be null

// Guard: null, empty, or whitespace
if (string.IsNullOrWhiteSpace(inputValue))
{
    Console.WriteLine("Cannot generate barcode: input value is null or empty.");
    return;
}

// Guard: format-specific constraints (example: EAN-8 requires 7-8 digits)
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;
}

GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);
barcode.SaveAsPng("output-barcode.png");
using IronBarCode;

string inputValue = GetValueFromUserOrDatabase(); // Could be null

// Guard: null, empty, or whitespace
if (string.IsNullOrWhiteSpace(inputValue))
{
    Console.WriteLine("Cannot generate barcode: input value is null or empty.");
    return;
}

// Guard: format-specific constraints (example: EAN-8 requires 7-8 digits)
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;
}

GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);
barcode.SaveAsPng("output-barcode.png");
$vbLabelText   $csharpLabel

IronBarcode的写入API执行其自己的内部验证——它检查校验和,验证长度限制,并拒绝所选编码中无效的字符。 这些检查会抛出携带描述性信息的System.Exception。 上述防御子句在问题到达库之前捕捉到问题,这使我们对错误信息和流程具有控制权。 有关支持的编码及其约束的完整列表,请参阅条码创建指南从数据创建条码指南

如何在下游处理前验证结果?

当条码数据输入到另一系统中——数据库写入、API调用、标签打印机时——我们需要一个验证闸门,在移交前检查结果计数、个别值完整性和条码类型。 这将空检查逻辑合并到一个可重用的方法中。

using IronBarCode;
using System.Collections.Generic;
using System.Linq;

public static class BarcodeValidator
{
    public static List<BarcodeResult> GetValidResults(
        string imagePath,
        BarcodeEncoding? expectedType = null,
        double minimumConfidence = 0.7)
    {
        BarcodeResults results = BarcodeReader.Read(imagePath);

        if (results is null || results.Count == 0)
            return new List<BarcodeResult>();

        return results
            .Where(r => !string.IsNullOrWhiteSpace(r.Value))
            .Where(r => r.Confidence >= minimumConfidence)
            .Where(r => expectedType == null || r.BarcodeType == expectedType)
            .ToList();
    }
}

// Usage
var validated = BarcodeValidator.GetValidResults(
    "warehouse-scan.png",
    expectedType: BarcodeEncoding.Code128,
    minimumConfidence: 0.85);

if (validated.Count == 0)
{
    // No valid results — log and skip downstream processing
    return;
}

// Safe to pass to downstream systems
foreach (var barcode in validated)
{
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString());
}
using IronBarCode;
using System.Collections.Generic;
using System.Linq;

public static class BarcodeValidator
{
    public static List<BarcodeResult> GetValidResults(
        string imagePath,
        BarcodeEncoding? expectedType = null,
        double minimumConfidence = 0.7)
    {
        BarcodeResults results = BarcodeReader.Read(imagePath);

        if (results is null || results.Count == 0)
            return new List<BarcodeResult>();

        return results
            .Where(r => !string.IsNullOrWhiteSpace(r.Value))
            .Where(r => r.Confidence >= minimumConfidence)
            .Where(r => expectedType == null || r.BarcodeType == expectedType)
            .ToList();
    }
}

// Usage
var validated = BarcodeValidator.GetValidResults(
    "warehouse-scan.png",
    expectedType: BarcodeEncoding.Code128,
    minimumConfidence: 0.85);

if (validated.Count == 0)
{
    // No valid results — log and skip downstream processing
    return;
}

// Safe to pass to downstream systems
foreach (var barcode in validated)
{
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString());
}
$vbLabelText   $csharpLabel

验证器方法返回一个空列表而不是空值——这样就不需要调用者对返回值进行空检查,这是标准的防御模式。 可选的expectedType参数确保下游系统仅接收它期望的条码格式,这防止了当扫描从同一图像中同时拾取到QR码和Code 128时的格式不匹配。

对于跨多个文件的批量读取,针对每个文件应用相同的模式并汇总结果。 ExpectBarcodeTypes在扫描级别进行过滤,这样减少了验证前的噪音。

下一步

IronBarcode操作的空检查归结为两种模式:在读取属性前保护BarcodeResults集合(空+空),以及在写入前验证输入字符串。 上述可重用验证器将两个关注点集中在一起。

要获得更深入的覆盖,请探索用于扫描配置的条码读取教程,用于所有BarcodeResult属性的输出数据格式指南,以及完整类型表面的API参考

开始免费的30天试用以针对实际扫描数据测试这些模式。 准备好后,查看许可选项起价$499。

常见问题解答

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

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

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

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

IronBarcode如何帮助空检查?

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

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

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

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

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

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

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

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

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

Curtis Chau
技术作家

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

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

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

还在滚动吗?

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