如何在 C# 中处理条码操作的空值检查
IronBarcode在 C# 中以 BarcodeResults 集合的形式返回扫描结果,直到 BarcodeReader.Read。 如果输入图像无法识别,则此方法返回 null;如果未检测到条形码,则返回空集合。 BarcodeWriter.CreateBarcode 如果输入为空、为空或格式无效,则会抛出异常。
现实世界中的扫描源,例如摄像头画面、文档上传和仓库扫描仪,可能并不总是能提供可读的条形码。 访问结果属性或遍历集合而不检查空值或 null 值可能会导致运行时异常 NullReferenceException。将无效字符串传递给写入 API 可能会导致 ArgumentException 异常。 在读取和写入操作中使用保护子句有助于防止生产环境中出现这些异常。
本文解释了如何使用 guard 子句、置信度过滤和可重用的验证器模式来处理IronBarcode读取和写入操作中的 null 和空结果。
快速开始:处理条码操作中的空结果
使用 IronBarcode 的 guard 模式,在访问任何结果属性之前安全地检查 BarcodeResults 集合。 立即阅读并查看以下简要内容,开始学习:
-
使用 NuGet 包管理器安装 https://www.nuget.org/packages/BarCode
PM > Install-Package BarCode -
复制并运行这段代码。
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); -
部署到您的生产环境中进行测试
通过免费试用立即在您的项目中开始使用IronBarcode
如何使用IronBarcode处理条形码操作中的空值检查
- 从NuGet下载IronBarcode库
- 调用
BarcodeReader.Read并捕获BarcodeResults返回值 - 在访问任何结果之前,请先检查是否为空。
- 在下游使用前,请验证各个
BarcodeResult属性。 - 在
BarcodeReaderOptions中设置ConfidenceThreshold,以在扫描级别过滤低质量读取。
如何处理条码结果的空和空结果?
有两种故障模式:如果输入不是有效图像,则 BarcodeResults 为 null;如果图像不包含条形码,则为空。 访问 Value,或者在未验证两个条件的情况下进行迭代,都会导致运行时异常。
进入处理循环前,请检查以下两个条件:
输入
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
每个 BarcodeResult 都提供 Value 和 Text 字符串属性,这两个属性都返回解码后的条形码内容。 条形码严重损坏或扫描不完整可能会产生空白值或空格值。 在每个结果上使用 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}");
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
如何将空安全模式应用于条码写入?
BarcodeWriter.CreateBarcode 接受一个字符串值和一个 BarcodeWriterEncoding 或 BarcodeEncoding 枚举。 传递 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");
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")
输出
有效的 7 位数字输入(1234567)会生成可扫描的 EAN-8 条形码。 空值、空值或非数字输入会被保护子句捕获,永远不会到达编码步骤。
写入 API 也会进行内部验证:它会检查校验和、验证长度限制,并拒绝所选编码的无效字符。 上述的保护条款可以及早发现问题,使调用者能够控制错误消息和恢复路径。 有关支持的编码及其约束的完整列表,请参阅条码创建指南和从数据创建条码指南。
如何在下游处理之前验证结果?
当条形码数据被导入到另一个系统(数据库写入、API 调用、标签打印机)时,最好在传递数据之前,将结果计数、值完整性和类型检查整合到一个可重用的方法中:
输入
使用 Code128 条形码仓库扫描作为验证器的读取目标。
: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
该方法返回空列表而不是 null,因此调用者永远不需要检查返回值是否为 null。 可选的 expectedType 参数按符号体系进行过滤,这样可以防止下游系统在扫描从同一图像中同时获取二维码和 Code 128 时接收到意外的格式。
对于跨多个文件的批量读取,对每个文件应用相同的模式并汇总结果。 ExpectBarcodeTypes 选项在 BarcodeReaderOptions 上预先缩小扫描范围至预期符号体系,从而减少到达验证器的不必要结果。
进一步阅读
-条形码读取教程:扫描配置和读取选项。
-输出数据格式指南:所有 BarcodeResult 属性及其类型。
-从数据创建条形码:每种符号体系的编码约束。
- BarcodeReaderOptions API 参考:完整的配置文档。
- IronBarcode更新日志:版本特定的修复和功能添加。
当管道准备就绪投入生产时,请查看许可选项。
常见问题解答
BarCode操作中的空值检查是什么?
BarCode操作中的空值检查是指验证BarCode结果或输入是否为空,以防止运行时错误并确保BarCode处理顺畅。
在 C# BarCode 操作中,为什么空值检查很重要?
在 C# BARCODE 操作中,空值检查至关重要,它能避免异常,并确保应用程序在 BARCODE 数据缺失或无效时能够优雅地处理这些情况。
IronBarcode 如何协助进行空值检查?
IronBarcode 提供了内置方法,可轻松处理空值检查,使开发人员无需手动实现复杂的验证逻辑,即可安全地管理 BarCode 数据。
在 IronBarcode 中进行空值检查有哪些最佳实践?
最佳实践包括检查 BarCodeResults 是否为空值、在处理前验证输入数据,以及使用置信度过滤器来确保 BarCode 扫描结果的可靠性。
IronBarcode 能否根据置信度过滤结果以避免空输出?
是的,IronBarcode 支持按置信度级别过滤 BarCode 识别结果,这有助于减少空结果,并确保 BarCode 读取的高准确性。
是否有办法使用 IronBarcode 验证输入内容?
IronBarcode 支持对写入数据进行验证,以确保编码到 BarCode 中的数据正确且完整,从而避免 BarCode 生成过程中的问题。
如果未处理空BarCode结果会发生什么?
如果未处理BarCode结果为空的情况,可能会导致运行时异常并中断应用程序的流程,从而引发潜在的崩溃或操作错误。

