跳過到頁腳內容
.NET幫助

C# New(開發者的工作原理)

C# 中的 new 記元運算符關鍵字多才多藝,服務於語言中的多個基本功能。 從實例化對象到隱藏繼承的成員,了解它們的應用對於有效的 C# 開發至關重要。 本指南探索了 new 關鍵字的各種用途,提供了清晰的例子來說明其強大性和靈活性。 我們稍後在本指南中也將探索IronSoftware 的 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 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")
$vbLabelText   $csharpLabel

默認和無參構造函數

如果在類中沒有明確定義構造函數,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
$vbLabelText   $csharpLabel

高級物件創建技術

在 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
$vbLabelText   $csharpLabel

匿名類型

在需要臨時數據結構而不需要聲明正式類的情況下,匿名類型大放異彩。 通過使用屬性初始化器語法的 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
	}
$vbLabelText   $csharpLabel

物件初始化器

物件初始化器代表了一種語法便利,允許您創建類的實例並立即設置其屬性,而無需呼叫帶參數的構造函數。 這不僅使代碼更易讀,而且通過消除為不同情況創建多個構造函數的需要來減少錯誤的可能性。 物件初始化器在處理複雜對象時特別方便,使您能夠僅設置所需的屬性。

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
	}
}
$vbLabelText   $csharpLabel

區域函數和 lambda 表達式

C# 支持區域函數和 lambda 表達式,提高了代碼的靈活性和簡潔性。

區域函數

區域函數是在另一個方法的範圍內定義的方法,對於安排代碼和封裝功能是強大的工具。

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
$vbLabelText   $csharpLabel

Lambda 表達式

Lambda 表達式提供了一種簡潔的方式來編寫內聯表達式或方法,無需顯式委託類型。

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
$vbLabelText   $csharpLabel

在繼承中使用 '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
$vbLabelText   $csharpLabel

使用泛型了解 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 Class
$vbLabelText   $csharpLabel

在本例中,Container 可以創建 T 的實例,前提是 T 具有無參構造函數。 當開發需要創建對象但未知具體類型的庫或框架時,此功能是無價的。

IronPDF 简介

IronPDF - 用於 PDF 生成和操作的 C# 庫 作為一個強大的工具脱颖而出,利用 C# 的功能來處理 PDF 文件。 通過整合 IronPDF,開發人員可以通過熟悉的 C# 語法編程創建新的 從 HTML 字串、文件或 URL 創建的 PDF 文檔,操作現有 PDF 及提取內容,以及利用 new 關鍵字進行對象實例化。

IronPDF 在HTML 到 PDF轉換方麵表現出色,確保準確保持原始佈局和樣式。 它非常適合從網路內容生成 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 Class
$vbLabelText   $csharpLabel

代碼示例

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 Namespace
$vbLabelText   $csharpLabel

在本類 Program 片段中,new IronPdf.ChromePdfRenderer() 展示了 IronPDF 渲染器對象的實例化。 然後使用此對象從 HTML 字串創建新的 PDF,展示了第三方庫與 C# 對象創建模式的無縫整合。 IronPDF 需要使用 new 關鍵字來初始化其類,這是一個對於學習物件實例化和探索 C# 高級功能的開發人員而言的相關範例。

結論

C# 中的 new 關鍵字是面向對象編程的基石,使開發人員能夠用精確和簡便性實例化對象、管理繼承和利用泛型。 通過實際範例,從創建簡單類實例到利用像匿名類型和物件初始化器這樣的高級功能,本指南展示了 new 的多功能性和力量。

IronPDF 的整合展示了 C# 如何可以超越傳統應用程式的範疇,通過代碼生成和操作 PDF 文件。 IronPDF 為開發人員提供免費試用和許可證選項來探索其特點,許可證的價格具有競爭力。

常見問題解答

new 關鍵字如何促進 C# 中的物件實例化?

在 C# 中,new 關鍵字透過呼叫類別的建構函式以分配新物件的記憶體來促進物件實例化。這對於創建類別或結構的實例至關重要。

new 關鍵字在 C# 類別繼承中的角色是什麼?

在類別繼承中,new 關鍵字允許衍生類別引入一個與繼承成員同名的成員,有效隱藏基類成員而不覆寫它。

如何使用 C# 將 HTML 轉換為 PDF?

您可以使用 IronPDF 的功能在 C# 中將 HTML 轉換為 PDF。此庫允許將 HTML 字串和檔案渲染為 PDF,保持原始佈局和樣式。

C# 泛型中 new() 約束的目的何在?

C# 泛型中的 new() 約束指定型別參數必須具有公共無參數建構子,使類別或方法內能建立該泛型型別的實例。

物件初始值設定項如何使 C# 開發人員受益?

C# 中的物件初始值設定項允許開發人員在一個語句中創建類別的實例並設定其屬性,從而改善代碼可讀性並減少多個建構子的需求。

如何在 C# 中生成和操作 PDF?

您可以使用 IronPDF 庫在 C# 中生成和操作 PDF。它提供將 HTML 生成 PDF 的功能,操作現有的 PDF,並使用 C# 語法提取內容。

C# 中的匿名型別是什麼,您何時會使用它們?

C# 中的匿名型別用於創建輕量級、臨時的資料結構,不需正式聲明類別。它們在如 LINQ 查詢僅需部分屬性的情況下十分有用。

new 關鍵字如何增強 C# 中第三方庫的使用?

new 關鍵字通過允許開發人員從這些庫中實例化對象來增強 C# 中第三方庫的使用,例如創建 IronPDF 對象以生成來自 HTML 源的 PDF。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。