如何在C#中处理条码操作的空检查
IronBarcode通过BarcodeResults集合的扫描结果。 如果输入图像无法识别,则此方法返回 null;如果未检测到条形码,则返回空集合。 如果输入为空、无效或格式无效,BarcodeWriter.CreateBarcode将抛出异常。
现实世界中的扫描源,例如摄像头画面、文档上传和仓库扫描仪,可能并不总是能提供可读的条形码。 在不检查为空或无效值的情况下访问结果属性或迭代集合会导致在运行时ArgumentException。 在读取和写入操作中使用保护子句有助于防止生产环境中出现这些异常。
本操作指南解释了如何通过使用保护条款、信任过滤和可重用验证器模式来处理IronBarcode读写操作中的null和空结果。
快速开始:处理条码操作中的空结果
使用IronBarcode的保护模式在访问任何结果属性之前安全地检查BarcodeResults集合。 立即阅读并查看以下简要内容,开始学习:
-
1Install IronBarcode with NuGet Package Manager
-
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部署到您的生产环境中进行测试
通过免费试用立即在您的项目中开始使用IronBarcode
如何使用IronBarcode处理条形码操作中的空值检查
- 从NuGet下载IronBarcode库
- 调用
BarcodeReader.Read并捕获BarcodeResults返回值 - 在访问任何结果之前,请先检查是否为空。
- 在下游使用前,请验证各个
BarcodeResult属性。 - 在
BarcodeReaderOptions中设置ConfidenceThreshold,以在扫描级别过滤低质量读取。
如何处理条码结果的空和空结果?
有两种故障模式:如果输入不是有效图像,则BarcodeResults为null;如果图像不包含条码,则为空。 访问Value或迭代而不验证两个条件会导致运行时异常。
进入处理循环前,请检查以下两个条件:
输入
一个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}");
}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每个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}");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如何将空安全模式应用于条码写入?
BarcodeEncoding枚举。 传递 null 值或空字符串会立即抛出异常。 格式限制也适用: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");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位数字输入(EAN-8条码。 空值、空值或非数字输入会被保护子句捕获,永远不会到达编码步骤。

写入 API 也会进行内部验证:它会检查校验和、验证长度限制,并拒绝所选编码的无效字符。 上述的保护条款可以及早发现问题,使调用者能够控制错误消息和恢复路径。 有关支持的编码及其约束的完整列表,请参阅条码创建指南和从数据创建条码指南。
如何在下游处理之前验证结果?
当条形码数据被导入到另一个系统(数据库写入、API 调用、标签打印机)时,最好在传递数据之前,将结果计数、值完整性和类型检查整合到一个可重用的方法中:
输入
一个Code128条码仓库扫描用作验证器的读取目标。

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。 可选的Code 128时接收到意外格式。
对于跨多个文件的批量读取,对每个文件应用相同的模式并汇总结果。 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结果为空的情况,可能会导致运行时异常并中断应用程序的流程,从而引发潜在的崩溃或操作错误。
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 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。