.NET ヘルプ

C# nameof(開発者向けの動作方法)

更新済み 3月 6, 2024
共有:

C# 6.0で導入された'nameof'演算子は、プログラム要素をその名前で参照することと、ランタイムで発生する静かな破損動作の問題に対処するためのコンパイル時構造です。 その主な目的は、ハードコードされた文字列の必要性を排除し、より保守しやすく、エラーに強いアプローチを提供することです。 この記事では、C#のnameof演算子を探求しながら、次の内容を紹介します IronPDF NuGet プログラムによってPDFドキュメントを生成するためのライブラリ。

'nameof' 演算子の基本構文

「'nameof' 演算子の基本構文はシンプルです。」 要素を引数として取り、その名前を文字列として返します。 以下の例を考えてみてください:

static void Main()
{
 //string name
  string myVariable = nameof(myVariable);
}
static void Main()
{
 //string name
  string myVariable = nameof(myVariable);
}
Shared Sub Main()
 'string name
  Dim myVariable As String = NameOf(myVariable)
End Sub
VB   C#

この場合、「nameof(myVariable)' は、文字列入力 "myVariable" を返します。 オペレータは、変数、型、メンバーなど、さまざまなコード要素に適用できます。

「nameof」演算子の利点

コードの保守性

「nameof」オペレーターの際立った利点の一つは、コードの保守性への好影響です。 名前を文字列としてハードコーディングする代わりに、開発者は 'nameof' を使用することで、名前が変更されたときに自動的に参照が更新されるようにできます。

static void Main()
{
// Without using nameof
Logger.Log("Error: The variable 'myVariable' is null.");
// Using nameof for improved maintainability
Logger.Log($"Error: The variable '{nameof(myVariable)}' is null.");
}
static void Main()
{
// Without using nameof
Logger.Log("Error: The variable 'myVariable' is null.");
// Using nameof for improved maintainability
Logger.Log($"Error: The variable '{nameof(myVariable)}' is null.");
}
Shared Sub Main()
' Without using nameof
Logger.Log("Error: The variable 'myVariable' is null.")
' Using nameof for improved maintainability
Logger.Log($"Error: The variable '{NameOf(myVariable)}' is null.")
End Sub
VB   C#

コンパイル時の安全性

'nameof' は名前のタイプミスや不整合のリスクを排除することで、コンパイル時の安全性を向上させます。 変数名の綴り間違いや変更があるとコンパイル時にエラーが発生し、ランタイムでの問題が発生する可能性を減らします。

static void Main()
{
// Compile-time error if 'myVariable' is misspelled
string myVariable = nameof(myVariabell);
}
static void Main()
{
// Compile-time error if 'myVariable' is misspelled
string myVariable = nameof(myVariabell);
}
Shared Sub Main()
' Compile-time error if 'myVariable' is misspelled
Dim myVariable As String = NameOf(myVariabell)
End Sub
VB   C#

リファクタリングサポート

「'nameof' 演算子はリファクタリングツールとシームレスに統合され、変数、型、またはメンバーの名前を変更する際に煩わしさのない体験を提供します。」 すべての 'nameof' 参照は自動的に更新されます。

static void Main()
{
// Before renaming local variable 'myVariable' to 'newVariable'
string myVariable = nameof(myVariable);
// After renaming local variable  'myVariable' to 'newVariable'
string newVariable = nameof(newVariable);
}
static void Main()
{
// Before renaming local variable 'myVariable' to 'newVariable'
string myVariable = nameof(myVariable);
// After renaming local variable  'myVariable' to 'newVariable'
string newVariable = nameof(newVariable);
}
Shared Sub Main()
' Before renaming local variable 'myVariable' to 'newVariable'
Dim myVariable As String = NameOf(myVariable)
' After renaming local variable  'myVariable' to 'newVariable'
Dim newVariable As String = NameOf(newVariable)
End Sub
VB   C#

デバッグの強化

デバッグ中に、「nameof」を使用するとコードがより情報豊富で読みやすくなります。 ログステートメント、例外メッセージ、およびその他のデバッグ出力は簡潔で文脈に沿ったものになります。

static void Main()
{
// Without using nameof throw new ArgumentNullException("myVariable", "The variable cannot be null."); 
// Using nameof for improved debugging 
throw new ArgumentNullException(nameof(myVariable), "The variable cannot be null.");
}
static void Main()
{
// Without using nameof throw new ArgumentNullException("myVariable", "The variable cannot be null."); 
// Using nameof for improved debugging 
throw new ArgumentNullException(nameof(myVariable), "The variable cannot be null.");
}
Shared Sub Main()
' Without using nameof throw new ArgumentNullException("myVariable", "The variable cannot be null."); 
' Using nameof for improved debugging 
Throw New ArgumentNullException(NameOf(myVariable), "The variable cannot be null.")
End Sub
VB   C#

変数が宣言されていない場合、throw new ArgumentNullException nameof が例外をスローします。

'nameof' 演算子の実践的な使用例

リフレクション

リフレクションを使用する際、『nameof』演算子を使用すると、ハードコーディングされた文字列を使わずに型、プロパティ、またはメソッドの名前を取得することが簡単になります。

Type type = typeof(MyClass);
string typeName = nameof(MyClass);
Type type = typeof(MyClass);
string typeName = nameof(MyClass);
Dim type As Type = GetType([MyClass])
Dim typeName As String = NameOf([MyClass])
VB   C#

次の例のクラスMyClassはハードコードされた文字列として使用できますが、リフレクションを使用してクラス名を動的に取得することも可能です。 変数名タイプはクラス名を持ち、その後、nameofキーワードを使用してクラスインスタンスの名前を取得します。 それらは同じ名前ではありません。

ログ記録と例外処理

「nameof」はログ記述や例外メッセージにおいて非常に役立ち、それらをより読みやすく、エラーが発生しにくいものにします。

Logger.Log($"Error: The property '{nameof(MyClass.MyProperty)}' is out of range.");
Logger.Log($"Error: The property '{nameof(MyClass.MyProperty)}' is out of range.");
Logger.Log($"Error: The property '{NameOf([MyClass].MyProperty)}' is out of range.")
VB   C#

この例では、Person を表すシンプルなクラスを作成し、nameof 演算子を使用してログ記録とエラーメッセージを改善します。

using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }    
    //method name
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing."); // display string
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public string DoSomething()
{
}
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string
        person.LastName = "Doe"; // string
        // Display the full name string again
        person.DisplayFullName();
    }
}
using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }    
    //method name
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing."); // display string
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public string DoSomething()
{
}
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string
        person.LastName = "Doe"; // string
        // Display the full name string again
        person.DisplayFullName();
    }
}
Imports System
Friend Class Person
	Public Property FirstName() As String
	Public Property LastName() As String
	'method name
	Public Sub DisplayFullName()
		If String.IsNullOrEmpty(FirstName) String.IsNullOrEmpty(LastName) Then
			LogError($"Invalid name: {NameOf(FirstName)} or {NameOf(LastName)} is missing.") ' display string
		Else
			Console.WriteLine($"Full Name: {FirstName} {LastName}")
		End If
	End Sub
	Public Function DoSomething() As String
	End Function
	Private Sub LogError(ByVal errorMessage As String)
		Console.ForegroundColor = ConsoleColor.Red
		Console.WriteLine($"Error: {errorMessage}")
		Console.ResetColor()
	End Sub
End Class
Friend Class Program
	Shared Sub Main()
		' Create an instance of the Person class
		Dim person As New Person()
		' Attempt to display the full name
		person.DisplayFullName()
		' Set the properties
		person.FirstName = "John" ' string
		person.LastName = "Doe" ' string
		' Display the full name string again
		person.DisplayFullName()
	End Sub
End Class
VB   C#

説明

  1. 以下の内容を日本語に翻訳してください:

私たちには、FirstNameとLastNameプロパティを持つPersonクラスがあり、これらのプロパティが設定されているかどうかを確認してから、フルネームを表示するDisplayFullNameというメソッドがあります。

  1. メソッド名 DisplayFullName の内部で、nameof を使用します。(FirstName) とnameof(姓) プロパティ名を文字列リテラルとして参照する。 これはコードの可読性を向上させ、プロパティ名が変更された場合でも、プロパティの定義と対応するエラーメッセージの両方がコンパイル時に自動的に更新されることを保証します。

  2. メソッド名 LogError は、エラーメッセージにプロパティ名を動的に含めるために nameof を活用します。

  3. Main メソッド内で、Person クラスのインスタンスを作成し、プロパティを設定せずにフルネームを表示しようと試みた後、プロパティの定義を設定して再度フルネームを表示します。

    パブリック文字列DoSomethingは、nameof演算子を使用していくつかのビジネスロジックを実行できます。

    このプログラムを実行すると、コンパイラーのエラーメッセージが動的にプロパティ名を組み込んでいることがわかります。これにより、プロパティがどれが欠けているのかを特定しやすくなり、より多くの文脈を提供します。

    C# Nameof (開発者にとっての仕組み):図1 - プロパティ変更イベント

    この例は、nameof 演算子がコードの保守性を向上させる方法を示しています。プロパティ名が変更されたときに参照を自動的に更新し、開発中のエラーメッセージをより有益な詳細にすることで、コードの保守性が向上します。

IronPDFの紹介

IronPDF は、からのC# PDFライブラリです アイアンソフトウェア PDF生成およびリーダーとして使用できる。 ここでは、基本機能を紹介します。 詳細については、ドキュメントを参照してください。

IronPDFの際立った機能はその HTMLからPDF 機能、およびレイアウトやスタイルを保持。 ウェブコンテンツからPDFを生成するため、レポート、請求書、ドキュメントに最適です。 HTMLファイル、URL、およびHTML文字列はシームレスにPDFに変換できます。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

インストール

IronPDFはNuGetパッケージマネージャーコンソールまたはVisual Studioパッケージマネージャーを使用してインストールできます。

dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
VB   C#

C# Nameof(開発者向けの使い方):図2 - NuGetパッケージマネージャーの検索バーに「ironpdf」と入力してIronPDFをインストールします。

namespace OrderBy;
using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing.");
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public void PrintPdf()
    {
        Console.WriteLine("Generating PDF using IronPDF.");
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>";
// Create a new PDF document
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf"); 
    }
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an  instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string literal
        person.LastName = "Doe"; // string literal
        // Display the full name again
        person.DisplayFullName();
    }
}
namespace OrderBy;
using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing.");
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public void PrintPdf()
    {
        Console.WriteLine("Generating PDF using IronPDF.");
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>";
// Create a new PDF document
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf"); 
    }
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an  instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string literal
        person.LastName = "Doe"; // string literal
        // Display the full name again
        person.DisplayFullName();
    }
}
Imports System

Namespace OrderBy
	Friend Class Person
		Public Property FirstName() As String
		Public Property LastName() As String
		Public Sub DisplayFullName()
			If String.IsNullOrEmpty(FirstName) String.IsNullOrEmpty(LastName) Then
				LogError($"Invalid name: {NameOf(FirstName)} or {NameOf(LastName)} is missing.")
			Else
				Console.WriteLine($"Full Name: {FirstName} {LastName}")
			End If
		End Sub
		Public Sub PrintPdf()
			Console.WriteLine("Generating PDF using IronPDF.")
			Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>"
	ignore ignore ignore ignore ignore ignore ignore var pdfDocument = New ChromePdfRenderer()
			pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf")
		End Sub
		Private Sub LogError(ByVal errorMessage As String)
			Console.ForegroundColor = ConsoleColor.Red
			Console.WriteLine($"Error: {errorMessage}")
			Console.ResetColor()
		End Sub
	End Class
	Friend Class Program
		Shared Sub Main()
			' Create an  instance of the Person class
			Dim person As New Person()
			' Attempt to display the full name
			person.DisplayFullName()
			' Set the properties
			person.FirstName = "John" ' string literal
			person.LastName = "Doe" ' string literal
			' Display the full name again
			person.DisplayFullName()
		End Sub
	End Class
End Namespace
VB   C#

こちらでは、IronPDFを使用して、PrintPdfメソッド内で見られるローカル変数contentとpdfDocumentを使用してPDFを生成します。

出力

C# Nameof(開発者向けの動作方法):図3 - プログラム出力

PDF生成

C# Nameof(開発者のための仕組み):図4 - PDF出力

ライセンス(無料トライアル利用可能)

IronPDF. このキーはappsettings.jsonに配置する必要があります。

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

試用ライセンスを取得するためにメールアドレスを提供してください。

結論

C#の「nameof」演算子は、よりクリーンで安全、かつメンテナンスが容易なコードを求める開発者にとって欠かせないものとなっている。 コードの可読性を向上させる能力と、コンパイル時の安全性およびシームレスなリファクタリングサポートを備えているため、C# 開発者のツールキットには欠かせないツールとなっています。 開発コミュニティが 'nameof' 演算子を引き続き受け入れ活用する中で、それはC#プログラミングの未来を形作る上で重要な役割を果たすことが期待されています。 IronPDFは、迅速かつ簡単にPDFを生成するために使用できる便利なNuGetパッケージです。

< 以前
C# 演算子(開発者にとっての動作方法)
次へ >
HashSet C# (開発者向けの動作方法)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >