跳過到頁腳內容
.NET HELP

C# New (How It Works For Developers)

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 查詢非常有用,在 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 Expression

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 隱藏派生類中的成員並不會覆蓋相同的成員; 相反,它引入了一個有別於基類版本的新成員。

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

使用泛型瞭解新功能

泛型在 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 - A C# Library for PDF Generation and Manipulation 脫穎而出,成為使用 C# 功能處理 PDF 檔案的強大工具。 透過結合 IronPDF,開發人員可以程式化地從 HTML 字串、檔案或 URL 建立新的 PDF 文件,操作現有的 PDF,以及擷取內容,這一切都透過熟悉的 C# 語法,並利用 new 關鍵字來實作物件。

IronPDF 擅長於 HTML 至 PDF 的轉換,可確保精確保留原始版面與樣式。 它非常適合從網頁內容(如報告、發票和文件)建立 PDF。 IronPDF 支援 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
$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 提供 免費試用和授權選項,供開發人員探索其功能,授權起價具競爭力。

常見問題解答

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

在 C# 中,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 查詢等情況下非常有用,因為在這些情況下只需要屬性的子集。

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

新的關鍵字增強了 C# 中第三方函式庫的使用,允許開發人員從這些函式庫中實體化物件,例如創建 IronPDF 物件來從 HTML 來源生成 PDF。

Jacob Mellor,技術長 @ Team Iron
首席技術長

Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。

Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。