
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")預設和無參數構造函式
如果在類別中沒有顯式定義構造函式,則C#會提供一個預設構造函式。 然而,一旦定義了帶參數的構造函式,則必須顯式聲明無參數構造函式以備需要。
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
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 };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 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表達式
C#支持區域函式和lambda表達式,增強了程式碼的靈活性和簡潔性。
區域函式
區域函式是在其他方法範圍內定義的方法,是組織程式碼和封裝功能的強大工具。
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 SubLambda表達式
Lambda表達式提供了一種簡潔的方式來編寫內聯表達式或方法,而無需顯式委託型別。
Func<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: 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 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(Of T As {New})
Public Function CreateItem() As T
Return New T()
End Function
End Class在此範例中,Container可以建立T的實例,只要T有一個無參數構造函式。 當開發需要建立物件而無法提前確定特定型別的程式庫或框架時,此功能非常有價值。
IronPDF簡介
IronPDF – 用於PDF生成和操作的C#程式庫是一個利用C#能力處理PDF文件的強大工具。 通過納入IronPDF,開發者可以通過熟悉的C#語法從HTML字串、文件或URL中程式性地建立新的PDF文件,操縱現有的PDF,並提取內容,並利用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");
}
}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}");
}
}
}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為開發者提供免費試用和授權選項來探索其功能,授權價格具有競爭力。

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.
Related Articles


