C# New(开发者如何使用)
C# 中的 new 运算符关键字非常通用,在语言中发挥着多种重要功能。 从实例化对象到隐藏继承的成员,了解其应用对于有效的 C# 开发至关重要。 本指南探讨 new 关键字的各种用途,提供清晰的示例以展示其强大和灵活性。 我们还将在本指南后面介绍IronPDF库在Iron Software上的概述。
对象实例化简介
对象实例化是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")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 ClassPublic 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' 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 };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
}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
}
}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 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 SubPublic 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: 25Func<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: 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 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 ClassPublic 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 ClassPublic 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# 的熟悉语法,利用new关键字进行对象实例化,程序化地从 HTML 字符串创建新 PDF 文档、文件或 URL、操作现有的 PDF 问题和提取内容。
IronPDF在HTML到PDF转换方面表现出色,确保精确保留原始布局和样式。 它非常适合从基于Web的内容中创建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 ClassImports 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 NamespaceImports 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 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。