.NET 帮助

C# 新手指南(开发人员如何使用)

发布 2023年六月13日
分享:

C# 中的new操作符关键字用途广泛,在语言中具有多种基本功能。从实例化对象到隐藏继承成员,了解它们的应用对于有效的 C# 开发至关重要。本指南 探索 关键词的各种用途,并提供清晰的示例来说明它的强大功能和灵活性。我们还将探索 IronPDF 在本指南稍后部分,我们将介绍如何使用 "图书馆"。

对象实例化简介

对象实例化是 new 操作符创建类或结构体实例的过程。在 C# 中,这主要是通过 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# New(如何为开发人员工作):图 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# New(如何为开发人员工作):图 3 - 隐藏继承成员输出

了解新的泛型

在 C# 编程中,泛型引入了一种抽象级别,允许开发人员设计对泛型进行操作的类、方法和接口。与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#

在本例中,容器只要 T 有一个无参数的构造函数,就能创建 T 的实例。在开发需要创建对象但又不知道具体类型的库或框架时,这种功能非常宝贵。

IronPDF 简介

C# New(如何为开发人员工作):图 4 - IronPDF

IronPDF IronPDF 是一款使用 C# 功能处理 PDF 文件的强大工具。通过使用 IronPDF,开发人员可以通过编程创建新的 从 HTML 字符串生成 PDF 文档通过熟悉的 C# 语法,并利用new关键字进行对象实例化,您就可以创建 PDF、文件或 URL,操作现有 PDF 并提取内容。

代码示例

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#

在该类程序片段中,new IronPdf.ChromePdfRenderer() 演示了 IronPDF 渲染器对象的实例化。然后使用该对象从 HTML 字符串创建一个新的 PDF,展示了第三方库与 C# 对象创建模式的无缝集成。IronPDF 需要使用 new 关键字来启动它的类,这使它成为开发人员学习对象实例化和探索 C# 高级功能的相关示例。

输出

运行程序后,控制台会显示以下信息:

C# New(如何为开发人员工作):图 5 - 控制台输出

打开 PDF 文件后,你会看到这个:

C# New(如何为开发人员工作):图 6 - PDF 输出

结论

C# 中的 new 关键字是面向对象编程的基石,它使开发人员能够精确、轻松地实例化对象、管理继承和使用泛型。通过实际示例,从创建简单的类实例到利用匿名类型和对象初始化器等高级功能,本指南展示了new的多功能性和强大功能。

IronPDF 的集成展示了 C# 如何将其应用范围扩展到传统应用程序之外,允许通过代码生成和操作 PDF 文件。IronPDF 提供了 免费试用 供开发人员探索其功能,许可证起价为 $749。

< 前一页
C# 查找(开发人员如何使用)
下一步 >
C# 这 (它是怎么为开发人员工作的)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >