.NET ヘルプ

C# New(開発者向けの動作)

更新済み 6月 13, 2023
共有:

C#のnewオペレーターキーワードは多用途であり、言語内で複数の重要な機能を果たします。 オブジェクトのインスタンス化から継承されたメンバーの隠蔽まで、それらの適用方法を理解することは効果的なC#開発にとって重要です。 このガイド 新機能を探索する キーワードのさまざまな用途を示し、そのパワーと柔軟性を明確に説明する例を提供します。 また、次のことを探求します IronPDF このガイドの後半でライブラリをご紹介します。

オブジェクトのインスタンス化の紹介

オブジェクトのインスタンス化は、新しいオペレーターがクラスまたは構造体のインスタンスを作成するプロセスです。 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 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")
VB   C#

デフォルトコンストラクタとパラメータなしコンストラクタ

クラスに明示的にコンストラクタが定義されていない場合、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 Class
VB   C#

高度なオブジェクト作成技法

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
VB   C#

匿名型

匿名型は、一時データ構造を必要としながら正式なクラスを宣言するオーバーヘッドを避けたいシナリオで輝きを見せます。 プロパティ初期化子構文を使って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
	}
VB   C#

オブジェクト初期化子

オブジェクト初期化子は、構文上の利便性を表しており、パラメーター付きのコンストラクターを呼び出すことなく、クラスのインスタンスを作成し、そのプロパティを直ちに設定することができます。 これにより、コードの可読性が向上するだけでなく、異なるシナリオに対する複数のコンストラクタの必要性を排除することによって、エラーの発生率が低下します。 オブジェクト初期化子は特に複雑なオブジェクトを扱う際に便利で、必要なプロパティだけを設定することができます。

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
	}
}
VB   C#

ローカル関数とラムダ式

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 Sub
VB   C#

C# 新機能(開発者のための使い方): 図1 - ローカル関数の出力

ラムダ式

ラムダ式は、明示的なデリゲート型を必要とせずに、インライン式やメソッドを簡潔に記述する方法を提供します。

Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
Dim square As Func(Of Integer, Integer) = Function(x) x * x
Console.WriteLine(square(5)) ' Output: 25
VB   C#

C# 新機能(開発者向けの仕組み):図2 - ラムダ出力

継承で「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 Class
VB   C#

C# New(開発者向けの動作説明):図 3 - 継承されたメンバー出力の非表示

ジェネリックを使用した new の理解

ジェネリクスはC#プログラミングにおいて抽象化のレベルを導入し、開発者がジェネリック型で動作するクラス、メソッド、およびインターフェイスを設計できるようにします。newキーワードと組み合わせることで、ジェネリクスは型を動的にインスタンス化することを可能にし、コードの再利用性を高め、冗長性を減らすことができます。

ジェネリック型における new() 制約

最新の()constraint**はジェネリックを用いる際の基礎であり、ジェネリッククラスやメソッドの型引数がパブリックな引数なしコンストラクタを持つ必要があることを指定します。 この制約により、クラスやメソッド内でジェネリック型のインスタンスを作成できるようになり、ジェネリッククラスやメソッドがより柔軟で強力になります。

public class Container<T> where T : new() {
    public T CreateItem() {
        return new T(); //new T
    }
}
public class Container<T> where T : new() {
    public T CreateItem() {
        return new T(); //new T
    }
}
public class Container(Of T) where T : New() {
	public T CreateItem() { Return New T(); }
}
VB   C#

この例では、コンテナT が引数なしのコンストラクターを持つ場合に T** のインスタンスを作成できます。 この機能は、特定の型を事前に知らないライブラリやフレームワークを開発する際に、オブジェクト作成が必要な場合に非常に貴重です。

IronPDFの紹介

C# 新機能(開発者向けの動作):図4 - IronPDF

IronPDF 際立った強力なツールであり、C#の機能を活用してPDFファイルを操作します。 IronPDFを組み込むことで、開発者はプログラムによって新しい HTML文字列からのPDFドキュメントファイルまたはURL、既存のPDFを操作し、コンテンツを抽出し、C#の馴染みのある構文を使用してnewキーワードを活用してオブジェクトをインスタンス化します。

コード例

using IronPdf;
using System;
namespace IronPdfExample
{
    class Program
    {
//static void main
        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
        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
'static void main
		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
VB   C#

このクラスプログラムのスニペットでは、new IronPdf.ChromePdfRenderer() は、IronPDFレンダラーオブジェクトのインスタンス化を示しています。 このオブジェクトは、HTML文字列から新しいPDFを作成するために使用され、C#のオブジェクト作成パターンとサードパーティライブラリのシームレスな統合を示します。 IronPDFでは、そのクラスを初期化するためにnewキーワードの使用が必要です。これはオブジェクト初期化とC#の高度な機能を学ぶ開発者にとって、適切な例となります。

出力

プログラムを実行すると、コンソールに次のメッセージが表示されます:

C# 新規 (開発者のための仕組み): 図5 - コンソール出力

PDFファイルを開くと、以下のように表示されます。

C# 新機能 (開発者のための仕組み): 図6 - PDF出力

結論

C# の new キーワードは、オブジェクト指向プログラミングの基礎であり、開発者がオブジェクトをインスタンス化し、継承を管理し、ジェネリックを精度と容易さで利用できるようにします。 実用的な例を通じて、単純なクラスインスタンスの作成から匿名型やオブジェクト初期化子のような高度な機能の活用まで、このガイドはnewの多様性と強力さを示しています。

IronPDFの統合は、C#が従来のアプリケーションを超えてその範囲を拡大し、コードを通じてPDFファイルの生成と操作を可能にする方法を示しています。 IronPDFは 無料試用 開発者が機能を探索するために、ライセンスは $749 から始まります。

< 以前
C# 検索(開発者向けの動作方法)
次へ >
C# これは(開発者向けの作業方法)

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

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