C# New (開発者向けの仕組み)
C#のnew演算子キーワードは多用途で、言語内の複数の重要な機能を提供します。 オブジェクトのインスタンス化から継承されたメンバーの隠蔽に至るまで、その適用を理解することは効果的なC#開発に不可欠です。 このガイドでは、newキーワードのさまざまな使い方を探り、そのパワーと柔軟性を示す明確な例を提供します。 このガイドでは後でIron SoftwareのIronPDFライブラリ概要も探ります。
オブジェクトインスタンス化の紹介
オブジェクトのインスタンス化は、new 演算子がクラスまたは構造体のインスタンスを作成するプロセスです。 C#では、指定された型のコンストラクタを呼び出し、新しいオブジェクトのメモリを割り当てるnewキーワードを使用してこれを達成します。
newを使ったインスタンスの作成
オブジェクトのインスタンスを作成するには、new 演算子の後にクラス名と一組の括弧を置きます。 クラスにパラメータを取るコンストラクタがある場合、これらの括弧内に引数を提供する必要があります。
public class Book
{
public string Title { get; set; }
public Book(string title)
{
Title = title;
}
}
Book book = new Book("The C# Programming Language");Public Class Book
Public Property Title() As String
Public Sub New(ByVal title As String)
Me.Title = title
End Sub
End Class
Private book As New Book("The C# Programming Language")Public Class Book
Public Property Title() As String
Public Sub New(ByVal title As String)
Me.Title = title
End Sub
End Class
Private book As New Book("The C# Programming Language")デフォルトコンストラクタとパラメータレスコンストラクタ
C#では、クラスでコンストラクタが明示的に定義されていない場合、デフォルトコンストラクタが提供されます。 しかし、一度パラメータ付きのコンストラクタが定義されると、必要に応じてパラメータレスコンストラクタを明示的に宣言する必要があります。
public class ExampleClass
{
// Parameterless constructor
public ExampleClass()
{
// Initialization code here
}
}public class ExampleClass
{
// Parameterless constructor
public ExampleClass()
{
// Initialization code here
}
}Public Class ExampleClass
' Parameterless constructor
Public Sub New()
' Initialization code here
End Sub
End ClassPublic Class ExampleClass
' Parameterless constructor
Public Sub New()
' Initialization code here
End Sub
End Class高度なオブジェクトの作成技術
C#におけるオブジェクト作成は、クラスのインスタンス化に留まりません; それは、より効率的で読みやすく簡潔なコードのために言語の強力な機能を活用するためのゲートウェイです。 ここでは、配列の操作、型の使用、オブジェクトイニシャライザの活用といった高度な技術を探り、コード作成を効率化します。
配列とコレクション
C#で特定の配列型の配列を作成することは基本的なスキルですが、その微妙な違いがコード能力を向上させます。 newキーワードを使用することで、配列のタイプと含めるべき要素の数を指定して配列をインスタンス化できます。 これは、変数のコレクションを構造的に管理する上で重要です。 基本的な配列を超えて、newは複雑なデータ構造に対応する多次元配列やジャグ配列の作成を容易にします。
// Single-dimensional array
int[] numbers = new int[5]; // Initializes an array for 5 integers
// Multidimensional array
int[,] matrix = new int[3, 2]; // A 3x2 matrix
// Jagged array (an array of arrays)
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[4]; // First row has 4 columns
jaggedArray[1] = new int[5]; // Second row has 5 columns
jaggedArray[2] = new int[3]; // Third row has 3 columns// Single-dimensional array
int[] numbers = new int[5]; // Initializes an array for 5 integers
// Multidimensional array
int[,] matrix = new int[3, 2]; // A 3x2 matrix
// Jagged array (an array of arrays)
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[4]; // First row has 4 columns
jaggedArray[1] = new int[5]; // Second row has 5 columns
jaggedArray[2] = new int[3]; // Third row has 3 columns' Single-dimensional array
Dim numbers(4) As Integer ' Initializes an array for 5 integers
' Multidimensional array
Dim matrix(2, 1) As Integer ' A 3x2 matrix
' Jagged array (an array of arrays)
Dim jaggedArray(2)() As Integer
jaggedArray(0) = New Integer(3){} ' First row has 4 columns
jaggedArray(1) = New Integer(4){} ' Second row has 5 columns
jaggedArray(2) = New Integer(2){} ' Third row has 3 columns' Single-dimensional array
Dim numbers(4) As Integer ' Initializes an array for 5 integers
' Multidimensional array
Dim matrix(2, 1) As Integer ' A 3x2 matrix
' Jagged array (an array of arrays)
Dim jaggedArray(2)() As Integer
jaggedArray(0) = New Integer(3){} ' First row has 4 columns
jaggedArray(1) = New Integer(4){} ' Second row has 5 columns
jaggedArray(2) = New Integer(2){} ' Third row has 3 columns匿名型
匿名型は、正式なクラスを宣言する手間をかけずに一時的なデータ構造を必要とするシナリオで輝きます。 newにプロパティイニシャライザ構文を使用することで、即座にオブジェクトを作成できます。 この機能は、より大きなオブジェクトからプロパティのサブセットを選択する必要があるLINQクエリや、特定の型を作成せずにデータを迅速にグループ化する場合に非常に役立ちます。
var person = new { Name = "Alice", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
// In LINQ
var results = from p in people
select new { p.Name, p.Age };var person = new { Name = "Alice", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
// In LINQ
var results = from p in people
select new { p.Name, p.Age };Dim person = New With {
Key .Name = "Alice",
Key .Age = 30
}
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}")
' In LINQ
Dim results = From p In people
Select New With {
Key p.Name,
Key p.Age
}Dim person = New With {
Key .Name = "Alice",
Key .Age = 30
}
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}")
' In LINQ
Dim results = From p In people
Select New With {
Key p.Name,
Key p.Age
}オブジェクトイニシャライザ
オブジェクトイニシャライザは構文上の便利さを表しており、パラメータを伴うコンストラクタを呼び出すことなくクラスのインスタンスを作成し、直ちにそのプロパティを設定できます。 これにより、コードが読みやすくなるだけでなく、さまざまなシナリオに対する複数のコンストラクタの必要性をなくすことでエラーの可能性を減らします。 オブジェクトイニシャライザは特に複雑なオブジェクトを扱う場合に便利で、必要なプロパティだけを設定することが可能です。
public class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
public Point Location { get; set; }
}
Rectangle rect = new Rectangle
{
Width = 100,
Height = 50,
Location = new Point { X = 0, Y = 0 }
};public class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
public Point Location { get; set; }
}
Rectangle rect = new Rectangle
{
Width = 100,
Height = 50,
Location = new Point { X = 0, Y = 0 }
};Public Class Rectangle
Public Property Width() As Integer
Public Property Height() As Integer
Public Property Location() As Point
End Class
Private rect As New Rectangle With {
.Width = 100,
.Height = 50,
.Location = New Point With {
.X = 0,
.Y = 0
}
}Public Class Rectangle
Public Property Width() As Integer
Public Property Height() As Integer
Public Property Location() As Point
End Class
Private rect As New Rectangle With {
.Width = 100,
.Height = 50,
.Location = New Point With {
.X = 0,
.Y = 0
}
}ローカル関数とラムダ式
C#はローカル関数とラムダ式をサポートし、コードの柔軟性と簡潔さを向上させます。
ローカル関数
ローカル関数は他のメソッドの範囲内で定義されたメソッドであり、コードを整理し機能をカプセル化する上で強力なツールとなります。
public void PerformOperation()
{
int LocalFunction(int x)
{
return x * x;
}
Console.WriteLine(LocalFunction(5)); // Output: 25
}public void PerformOperation()
{
int LocalFunction(int x)
{
return x * x;
}
Console.WriteLine(LocalFunction(5)); // Output: 25
}Public Sub PerformOperation()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' int LocalFunction(int x)
' {
' Return x * x;
' }
Console.WriteLine(LocalFunction(5)) ' Output: 25
End SubPublic Sub PerformOperation()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
' int LocalFunction(int x)
' {
' Return x * x;
' }
Console.WriteLine(LocalFunction(5)) ' Output: 25
End Subラムダ式
ラムダ式は、明示的なデリゲート型を指定せずにインライン式やメソッドを簡潔に記述する方法を提供します。
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25Dim square As Func(Of Integer, Integer) = Function(x) x * x
Console.WriteLine(square(5)) ' Output: 25Dim square As Func(Of Integer, Integer) = Function(x) x * x
Console.WriteLine(square(5)) ' Output: 25継承での'new'の使用
クラスの継承では、newが継承されたメンバーを隠すことができ、派生クラスが基底クラスのメンバーと同じ名前のメンバーを導入できます。
継承されたメンバーの隠蔽
派生クラスでメンバーを非表示にするために new を使用しても、同じメンバーをオーバーライドするわけではありません。 代わりに、基底クラスのバージョンとは異なる新しいメンバーを導入します。
public class BaseClass
{
public void Display()
{
Console.WriteLine("Base display");
}
}
public class DerivedClass : BaseClass
{
public new void Display()
{
Console.WriteLine("Derived display");
}
}public class BaseClass
{
public void Display()
{
Console.WriteLine("Base display");
}
}
public class DerivedClass : BaseClass
{
public new void Display()
{
Console.WriteLine("Derived display");
}
}Public Class BaseClass
Public Sub Display()
Console.WriteLine("Base display")
End Sub
End Class
Public Class DerivedClass
Inherits BaseClass
Public Shadows Sub Display()
Console.WriteLine("Derived display")
End Sub
End ClassPublic Class BaseClass
Public Sub Display()
Console.WriteLine("Base display")
End Sub
End Class
Public Class DerivedClass
Inherits BaseClass
Public Shadows Sub Display()
Console.WriteLine("Derived display")
End Sub
End Classジェネリクスにおけるnewの理解
ジェネリクスはC#プログラミングに抽象レベルを導入し、開発者がジェネリック型で動作するクラス、メソッド、インタフェースを設計できるようにします。newキーワードと組み合わせると、ジェネリクスはタイプを動的にインスタンス化する力を与え、コードの再利用性を高め冗長性を減らします。
ジェネリック型におけるnew()制約
new()制約は、ジェネリックスにおけるnewの使用の基礎であり、ジェネリッククラスやメソッドの型引数が公開されているパラメータなしのコンストラクタを持つ必要があることを指定します。 この制約により、ジェネリック型のインスタンスをクラスやメソッド内で作成でき、ジェネリッククラスやメソッドはより柔軟で強力になります。
public class Container<t> where T : new()
{
public T CreateItem()
{
return new T();
}
}public class Container<t> where T : new()
{
public T CreateItem()
{
return new T();
}
}Public Class Container(Of T As {New})
Public Function CreateItem() As T
Return New T()
End Function
End ClassPublic Class Container(Of T As {New})
Public Function CreateItem() As T
Return New T()
End Function
End Classこの例では、Containerが、Tがパラメータなしのコンストラクタを持っていれば、Tのインスタンスを作成できます。 この機能は、特定のタイプを事前に知らずにライブラリやフレームワークを開発する際に非常に価値があります。
IronPDFの紹介
IronPDF – C#を使ったPDF生成と操作のためのライブラリは、PDFファイルを操作するためにC#の機能を活用した強力なツールとして際立っています。 IronPDFを組み込むことで、開発者はHTML文字列、ファイル、またはURLから新しいPDFドキュメントをプログラムで作成し、既存のPDFを操作したり、C#の馴染み深い構文を使ってコンテンツを抽出したりできます。newキーワードを活用してオブジェクトをインスタンス化します。
IronPDF は HTML から PDF への変換に秀でており、元のレイアウトとスタイルを正確に保存します。 これは、レポート、請求書、ドキュメントなどの Web ベースのコンテンツから PDF を作成するのに最適です。 HTML ファイル、URL、または生の HTML 文字列のサポートにより、IronPDF は高品質な 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 ClassImports 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コード例
using IronPdf;
using System;
namespace IronPdfExample
{
class Program
{
static void Main(string[] args)
{
IronPdf.License.LicenseKey = "License-Key";
// Create a new PDF document from HTML content
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1><p>This is a PDF generated from HTML using IronPDF.</p>");
// Save the PDF to a file
string filePath = "HelloWorld.pdf";
pdf.SaveAs(filePath);
// Confirmation message
Console.WriteLine($"PDF file has been generated at: {Environment.CurrentDirectory}\\{filePath}");
}
}
}using IronPdf;
using System;
namespace IronPdfExample
{
class Program
{
static void Main(string[] args)
{
IronPdf.License.LicenseKey = "License-Key";
// Create a new PDF document from HTML content
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1><p>This is a PDF generated from HTML using IronPDF.</p>");
// Save the PDF to a file
string filePath = "HelloWorld.pdf";
pdf.SaveAs(filePath);
// Confirmation message
Console.WriteLine($"PDF file has been generated at: {Environment.CurrentDirectory}\\{filePath}");
}
}
}Imports IronPdf
Imports System
Namespace IronPdfExample
Friend Class Program
Shared Sub Main(ByVal args() As String)
IronPdf.License.LicenseKey = "License-Key"
' Create a new PDF document from HTML content
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1><p>This is a PDF generated from HTML using IronPDF.</p>")
' Save the PDF to a file
Dim filePath As String = "HelloWorld.pdf"
pdf.SaveAs(filePath)
' Confirmation message
Console.WriteLine($"PDF file has been generated at: {Environment.CurrentDirectory}\{filePath}")
End Sub
End Class
End NamespaceImports IronPdf
Imports System
Namespace IronPdfExample
Friend Class Program
Shared Sub Main(ByVal args() As String)
IronPdf.License.LicenseKey = "License-Key"
' Create a new PDF document from HTML content
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1><p>This is a PDF generated from HTML using IronPDF.</p>")
' Save the PDF to a file
Dim filePath As String = "HelloWorld.pdf"
pdf.SaveAs(filePath)
' Confirmation message
Console.WriteLine($"PDF file has been generated at: {Environment.CurrentDirectory}\{filePath}")
End Sub
End Class
End Namespaceこのクラス Program スニペットでは、new IronPdf.ChromePdfRenderer() が IronPDFレンダラーオブジェクトのインスタンス化を示しています。 このオブジェクトは、HTML文字列から新しいPDFを作成するために使用され、C#のオブジェクト作成パターンとサードパーティライブラリのシームレスな統合を示しています。 IronPDFは、そのクラスを起動するためにはnewキーワードの使用を必要とし、オブジェクトインスタンス化について学び、C#の高度な機能を探る開発者にとって関連性のある例です。
結論
C#のnewキーワードは、オブジェクト指向プログラミングの基礎であり、開発者はオブジェクトをインスタンス化し、継承を管理し、ジェネリクスを正確かつ容易に利用できます。 クラスの単純なインスタンスの作成から匿名型やオブジェクトイニシャライザといった高度な機能の活用に至るまでの実践的な例を通じて、このガイドはnewの多用途性と力を示しています。
IronPDFの統合は、C#が伝統的なアプリケーションを超えてその到達範囲を拡大し、コードを通じてPDFファイルの生成と操作を可能にしていることを示しています。 IronPDFは、その機能を試すための無料トライアルとライセンスオプションを提供しており、ライセンスは競争力のある価格で開始します。
ジェイコブ・メラーはIron Softwareの最高技術責任者(CTO)であり、C# PDFテクノロジーを開拓する先見的なエンジニアです。Iron Softwareのコアコードベースを支えるオリジナル開発者として、彼は創業以来、会社の製品アーキテクチャを形成し、CEOのCameron Rimingtonとともに、会社をNASA、Tesla、および世界的な政府機関にサービスを提供する50人以上の会社に変えました。1999年にロンドンで最初のソフトウェアビジネスを開業し、2005年に最初 for .NETコンポーネントを作成した後、Microsoftのエコシステム全体で複雑な問題を解決することを専門としました。