.NET 幫助

C# 新手指南 (開發者使用方式)

發佈 2023年6月13日
分享:

在 C# 中,new 運算子關鍵字功能多樣,在語言中具有多個基本作用。從實例化物件到隱藏繼承的成員,理解它們的應用對於有效的 C# 開發至關重要。本指南 探索 關鍵字的各種用途,提供清晰的例子來說明其威力和彈性。我們還將探討 IronPDF 本指南稍後將介紹該庫。

物件實例化介紹

物件實例化(Object instantiation)是使用 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")
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#

區域函式和 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
VB   C#

C# 新增功能(對開發人員的運作方式):圖1 - 本地函數輸出

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

C# 新手(對開發者的運作方式):圖 2 - Lambda 輸出

繼承中使用 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# 新特性(開發人員如何使用):圖 3 - 隱藏繼承成員輸出

理解具有泛型的 new 關鍵字

泛型在 C# 程式設計中引入了一層抽象,允許開發者設計可操作泛型類型的類別、方法和介面。當與 new 關鍵字結合時,泛型使您能夠動態地實例化類型,進一步增強了程式碼的可重用性並減少了冗餘。

新()泛型類型的限制

new()約束是使用new**與泛型的基石,指定泛型類別或方法中的型別參數必須具有公共的無參數建構函式。此約束使您能夠在類別或方法內建立泛型類型的實例,使您的泛型類別和方法更加靈活和強大。

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#

在此範例中,Container能夠創建 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#

在這個類Program片段中,new IronPdf.ChromePdfRenderer() 演示了 IronPDF 渲染器對象的實例化。該對象隨後用於從 HTML 字符串創建新的 PDF,展示了第三方庫與 C# 對象創建模式的無縫集成。IronPDF 需要使用 new 關鍵字來啟動它的類,這對於學習對象實例化和探索 C# 高級功能的開發人員來說是個相關的例子。

輸出

當您運行程式時,您會在控制台上看到以下訊息:

C#新功能(對開發人員的運作方式):圖5 - 控制台輸出

一旦你打開 PDF 文件,你會看到這個:

C# 新手入門(對開發者的運作方式):圖6 - PDF輸出

結論

new 關鍵字在 C# 中是物件導向程式設計的基石,使開發者能夠實例化物件、管理繼承以及利用泛型,以精確和簡便的方式進行操作。透過實際範例,從創建簡單的類別實例到運用匿名類型和物件初始化等高級功能,本指南展示了 new 的多樣性和強大功能。

IronPDF 的集成展示了 C# 如何超越傳統應用,透過程式碼生成和操作 PDF 文件。IronPDF 提供了 免費試用 供開發人員探索其功能,授權起始價格為 $749。

< 上一頁
C# 查找(開發者使用方式)
下一個 >
C# 這個(它如何為開發者工作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >