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")
預設與無參數構成程式
如果類別中沒有明確定義構造器,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
進階物件建立技巧
在 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
匿名類型
匿名類型在需要臨時資料結構的場景中大放異彩,而無需宣告正式類別的開銷。 透過使用 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
}
物件初始化器
物件初始化器代表一種語法上的便利,允許您建立一個類的實體,並立即設定其屬性,而不需要呼叫帶有參數的建構器。 這不僅讓程式碼更具可讀性,也可藉由省去針對不同情境的多重建構器來降低出錯的可能性。 物件初始化器在處理複雜的物件時特別方便,可以讓您只設定所需的屬性。
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
}
}
本地函數和 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
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
在繼承中使用 '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
使用泛型瞭解新功能
泛型在 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
在這個例子中,容器可以創建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
程式碼範例
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
在這類 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。



