IronBarcode ハウツー ヌルチェック バーコード操作におけるNullチェックをC#で処理する方法 カーティス・チャウ 更新日:2026年3月4日 IronBarcode をダウンロード NuGet ダウンロード DLL ダウンロード 無料トライアル LLM向けのコピー LLM向けのコピー LLM 用の Markdown としてページをコピーする ChatGPTで開く このページについてChatGPTに質問する ジェミニで開く このページについてGeminiに問い合わせる Grokで開く このページについてGrokに質問する 困惑の中で開く このページについてPerplexityに問い合わせる 共有する Facebook で共有 Xでシェア(Twitter) LinkedIn で共有 URLをコピー 記事をメールで送る This article was translated from English: Does it need improvement? Translated View the article in English IronBarcode は、C# から BarcodeReader.Read まで、スキャン結果を BarcodeResults コレクションとして返します。 このメソッドは、入力画像が認識されない場合は null を返し、バーコードが検出されない場合は空のコレクションを返します。 BarcodeWriter.CreateBarcode 入力が null、空、または無効な形式の場合、例外がスローされます。 カメラ映像、文書アップロード、倉庫のスキャナーなど、実際のスキャン元では、必ずしも読み取り可能なバーコードが得られるとは限りません。 結果プロパティにアクセスしたり、null 値や空値をチェックせずにコレクションを反復処理したりすると、実行時に NullReferenceException が発生する可能性があります。書き込み API に無効化文字列を渡すと、ArgumentException が発生する可能性があります。 読み取り操作と書き込み操作の両方でガード句を使用することで、本番環境でこれらの例外が発生するのを防ぐことができます。 このハウツーでは、ガード句、信頼度フィルタリング、および再利用可能なバリデーターパターンを使用して、 IronBarcodeの読み取りおよび書き込み操作でnullおよび空の結果を処理する方法について説明します。 クイックスタート: バーコード操作でNull結果を処理する IronBarcodeのガードパターンを使用して、結果プロパティにアクセスする前にBarcodeResultsコレクションを安全にチェックします。 まずは、この簡単な読み物とチェック項目から始めてみましょう。 IronBarcode をNuGetパッケージマネージャでインストール 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 を使い始めましょう無料トライアル Free 30 Day Trial IronBarcodeを使用したバーコード操作におけるヌルチェックの処理方法 NuGetからIronBarcodeライブラリをダウンロード BarcodeReader.Readを呼び出し、 BarcodeResults戻り値を取得します。 結果にアクセスする前にnullかどうかを確認してください。 下流で使用する前に、個々のBarcodeResultプロパティを検証してください。 BarcodeReaderOptionsのConfidenceThresholdを設定して、スキャンレベルで低品質の読み取りをフィルタリングします。 Nullおよび空のバーコード結果をどのように処理しますか? 失敗モードは 2 つあります。入力が有効な画像でない場合は 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}"); } $vbLabelText $csharpLabel 各 BarcodeResult は、Value および Text の文字列プロパティを提供し、どちらもデコードされたバーコードの内容を返します。 ひどく損傷したバーコードや部分的なスキャンでは、空白の値や空白文字が表示される場合があります。 空の値が下流システムに渡らないように、各結果に string.IsNullOrWhiteSpace を使用してください。 BarcodeReaderOptions には、結果コレクションに到達する前に低品質のリードを破棄するプロパティ (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 バーコード書き込みにNullセーフパターンを適用する方法 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"); $vbLabelText $csharpLabel 出力 有効な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 } $vbLabelText $csharpLabel このメソッドはnullではなく空のリストを返すため、呼び出し側は戻り値のnullチェックを行う必要がありません。 オプションの expectedType パラメータはシンボル体系でフィルタリングを行い、スキャンによって同じ画像から QR コードと Code 128 の両方が検出された場合に、下流システムが予期しない形式を受信するのを防ぎます。 複数のファイルに対して一括読み込みを行う場合は、ファイルごとに同じパターンを適用し、結果を集計します。 BarcodeReaderOptions の ExpectBarcodeTypes オプションは、事前に想定されるシンボル体系にスキャンを絞り込むため、不要な結果がバリデーターに到達する可能性が低くなります。 さらなる読み物 -バーコード読み取りチュートリアル:スキャン設定と読み取りオプション。 -出力データ形式ガイド:すべての BarcodeResult プロパティとその型。 -データからバーコードを作成する:各シンボル体系のエンコード制約。 BarcodeReaderOptions APIリファレンス:完全な設定ドキュメント。 IronBarcodeの変更履歴:バージョン固有の修正と機能追加。 パイプラインが本番稼働準備完了になったら、ライセンスオプションを確認してください。 よくある質問 バーコード操作でのnullチェックとは何ですか? バーコード操作でのnullチェックは、ランタイムエラーを防ぎ、スムーズなバーコード処理を保証するためにバーコード結果や入力がnullであるかを確認することを含みます。 C#バーコード操作でnullチェックが重要なのはなぜですか? nullチェックは、例外を回避し、バーコードデータが不足または無効である場合でもアプリケーションがうまく処理できるようにするため、C#バーコード操作で重要です。 IronBarcodeはどのようにnullチェックをサポートしますか? IronBarcodeは、複雑な検証ロジックを手動で実装せずにバーコードデータを安全に管理できるようにするための組み込みのメソッドを提供しています。 IronBarcodeでのnullチェックのベストプラクティスは何ですか? ベストプラクティスには、BarcodeResultsのnull値をチェックし、処理前に入力を検証し、信頼度フィルターを使用して信頼性のあるバーコードスキャン結果を確保することが含まれます。 IronBarcodeはnull出力を避けるために信頼度で結果をフィルタリングできますか? はい、IronBarcodeはバーコード結果を信頼度でフィルタリングし、null出力を減らし、バーコード読み取りの精度を保証します。 IronBarcodeを使用して書き込み入力を検証する方法はありますか? IronBarcodeを使用すると、バーコードにエンコードされるデータが正しく完全であることを確認するために書き込み入力を検証し、バーコード生成時の問題を防ぎます。 nullバーコード結果が処理されない場合はどうなりますか? nullバーコード結果が処理されないと、それはランタイム例外を引き起こし、アプリケーションの流れを中断させ、潜在的なクラッシュや不正確な操作を引き起こす可能性があります。 カーティス・チャウ 今すぐエンジニアリングチームとチャット テクニカルライター Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。 準備はできましたか? Nuget ダウンロード 2,121,847 | バージョン: 2026.3 リリース 無料トライアル NuGet 無料ダウンロード 総ダウンロード数: 2,121,847 ライセンスを見る まだスクロールしていますか? すぐに証拠が欲しいですか? PM > Install-Package BarCode サンプルを実行する 文字列が BarCode になるのを見る。 NuGet 無料ダウンロード 総ダウンロード数: 2,121,847 ライセンスを見る