.NET 帮助

C# 这 (它是怎么为开发人员工作的)

在 C# 中,有一个特别重要的关键字,就是 this 关键字。 该关键字指的是使用它的当前类实例。 除其他外,它还可用于区分同名的类级变量和方法参数。 例如,如果您有一个实例变量和一个同名的方法参数,this 可以成为救星!

该关键词的基础知识

在一个公共类中,例如 Employee,您可能会有像 idname 这样的公共实例变量。 如果您想在方法中为这些实例变量赋值,您可能会遇到一个常见问题:如果方法参数与实例变量同名怎么办?

这是一个解决方案:使用this关键字在C#文档中! 在以下公共类Employee中的方法示例中,使用this关键字来区分实例变量和共享相同名称的方法参数。

public void Display(int id, string name)
{
    this.id = id;
    this.name = name;
}
public void Display(int id, string name)
{
    this.id = id;
    this.name = name;
}
Public Sub Display(ByVal id As Integer, ByVal name As String)
	Me.id = id
	Me.name = name
End Sub
$vbLabelText   $csharpLabel

在此情况下,this.id 指的是实例变量,而 id 是方法参数。

构造函数重载中的this关键字

通过利用this关键字,构造函数重载成为同一类中的一种强大技术。 当一个类,例如student类,具有多个带有不同参数的构造函数时,this关键字允许一个构造函数调用另一个构造函数,从而消除了冗余代码的需要。

考虑以下示例,其中this用在参数化构造函数中:

public class Student
{
    private string name;
    private int id;

    public Student() : this("Default", 0)
    {
    }

    public Student(string name, int id)
    {
        this.name = name;
        this.id = id;
    }
}
public class Student
{
    private string name;
    private int id;

    public Student() : this("Default", 0)
    {
    }

    public Student(string name, int id)
    {
        this.name = name;
        this.id = id;
    }
}
Public Class Student
	Private name As String
	Private id As Integer

	Public Sub New()
		Me.New("Default", 0)
	End Sub

	Public Sub New(ByVal name As String, ByVal id As Integer)
		Me.name = name
		Me.id = id
	End Sub
End Class
$vbLabelText   $csharpLabel

在无参数构造函数中,this("Default", 0) 调用参数化构造函数,将 Default 设置为名称和 ID。

在扩展方法中探索this

C# 中的扩展方法提供了一种在不修改原始类型的情况下为现有类型添加方法的方法。 这就是this关键字发挥奇妙作用的地方。 在扩展方法的参数列表中,它指的是被扩展的类型。

下面是一个扩展方法的例子:

public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}
public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}
Public Module StringExtensions
	<System.Runtime.CompilerServices.Extension> _
	Public Function IsNullOrEmpty(ByVal str As String) As Boolean
		Return String.IsNullOrEmpty(str)
	End Function
End Module
$vbLabelText   $csharpLabel

这里,this string str 告诉 C# 这是一个针对字符串类型的扩展方法。 现在您可以在任何字符串对象上使用此方法,例如if(myString.IsNullOrEmpty())

索引器中的this

this 关键字也可用于定义索引器。 索引器可以像数组一样对类的实例进行索引。 这有助于您使用类似索引的符号访问对象中的数据。 在索引器中,this 后跟一个数组索引,通常是 int index

下面是一个索引器的基本示例:

public class Test
{
    private int [] array = new int [100];

    public int this [int index]
    {
        get { return array [index]; }
        set { array [index] = value; }
    }
}
public class Test
{
    private int [] array = new int [100];

    public int this [int index]
    {
        get { return array [index]; }
        set { array [index] = value; }
    }
}
Public Class Test
	Private array(99) As Integer

	Default Public Property Item(ByVal index As Integer) As Integer
		Get
			Return array (index)
		End Get
		Set(ByVal value As Integer)
			array (index) = value
		End Set
	End Property
End Class
$vbLabelText   $csharpLabel

在这个类Test中,this关键字定义了一个索引器,可用于获取或设置array实例字段中的值。

this 和静态成员

需要注意的一点是,this 不能用于引用静态成员或方法。 这是因为this指的是当前实例,而静态成员属于类本身,而不是类的实例。

public class Program
{
    public static void Main(string [] args)
    {
        // Can't use `this` here, because 'Main' is a static method.
    }
}
public class Program
{
    public static void Main(string [] args)
    {
        // Can't use `this` here, because 'Main' is a static method.
    }
}
Public Class Program
	Public Shared Sub Main(ByVal args() As String)
		' Can't use `this` here, because 'Main' is a static method.
	End Sub
End Class
$vbLabelText   $csharpLabel

所以,记住,this 是用于实例的,不适用于类级别或静态成员!

this 关键字和属性

就像实例变量和方法参数一样,this关键字也可以用于属性。 在 C# 中,属性是一种成员,它为读取、写入或计算私有字段的值提供了灵活的机制。 属性可以作为公共数据成员使用,但它们实际上是一种特殊的方法,称为访问器。

我们来看一个在属性中使用this的简单示例:

public class Employee
{
    private string name;

    public string Name
    {
        get { return this.name; }
        set { this.name = value; }
    }
}
public class Employee
{
    private string name;

    public string Name
    {
        get { return this.name; }
        set { this.name = value; }
    }
}
Public Class Employee
'INSTANT VB NOTE: The field name was renamed since Visual Basic does not allow fields to have the same name as other class members:
	Private name_Conflict As String

	Public Property Name() As String
		Get
			Return Me.name_Conflict
		End Get
		Set(ByVal value As String)
			Me.name_Conflict = value
		End Set
	End Property
End Class
$vbLabelText   $csharpLabel

在上述类中,this关键字用于在Name属性的get和set访问器中引用私有字符串name

探索this 及委托

另一个出现this的地方是在委托中。 C# 中的委托类似于 C 或 C++ 中的函数指针。 这是一个引用类型的变量,用于保存方法的引用。 委托方法与扩展方法类似,可以使用this来访问当前实例。

以下是使用this的委托示例:

public delegate void DisplayDelegate();

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public void Display()
    {
        DisplayDelegate displayDelegate = new DisplayDelegate(this.DisplayDetails);
        displayDelegate();
    }

    private void DisplayDetails()
    {
        Console.WriteLine("ID: " + Id + ", Name: " + Name);
    }
}
public delegate void DisplayDelegate();

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public void Display()
    {
        DisplayDelegate displayDelegate = new DisplayDelegate(this.DisplayDetails);
        displayDelegate();
    }

    private void DisplayDetails()
    {
        Console.WriteLine("ID: " + Id + ", Name: " + Name);
    }
}
Public Delegate Sub DisplayDelegate()

Public Class Student
	Public Property Id() As Integer
	Public Property Name() As String

	Public Sub Display()
		Dim displayDelegate As New DisplayDelegate(AddressOf Me.DisplayDetails)
		displayDelegate()
	End Sub

	Private Sub DisplayDetails()
		Console.WriteLine("ID: " & Id & ", Name: " & Name)
	End Sub
End Class
$vbLabelText   $csharpLabel

在学生类中,this.DisplayDetails 创建一个新的委托实例,该实例引用当前对象的 DisplayDetails 方法。

在 IronPDF 中实现 this 关键字

让我们深入研究一个可能使用this关键字与IronPDF的例子,IronPDF 是一个强大的 .NET 库,用于编辑和使用 HTML 创建 PDF 文件

考虑一个名为PDFHandler的类,它使用IronPDF库对PDF文件执行各种操作:

using IronPdf;

public class PDFHandler
{
    private string path;

    public PDFHandler(string path)
    {
        this.path = path;
    }

    public void GeneratePDF(string content)
    {
        var Renderer = new IronPdf.ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(content);
        PDF.SaveAs(this.path);
    }
}
using IronPdf;

public class PDFHandler
{
    private string path;

    public PDFHandler(string path)
    {
        this.path = path;
    }

    public void GeneratePDF(string content)
    {
        var Renderer = new IronPdf.ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(content);
        PDF.SaveAs(this.path);
    }
}
Imports IronPdf

Public Class PDFHandler
	Private path As String

	Public Sub New(ByVal path As String)
		Me.path = path
	End Sub

	Public Sub GeneratePDF(ByVal content As String)
		Dim Renderer = New IronPdf.ChromePdfRenderer()
		Dim PDF = Renderer.RenderHtmlAsPdf(content)
		PDF.SaveAs(Me.path)
	End Sub
End Class
$vbLabelText   $csharpLabel

在这个PDFHandler类中,this关键字用于引用当前实例的path字段。 此字段用于将生成的 PDF 保存到指定路径。

当我们创建一个新的PDFHandler实例并调用GeneratePDF方法时,this关键字允许我们使用在对象创建期间指定的path

class Program
{
    static void Main(string [] args)
    {
        PDFHandler pdfHandler = new PDFHandler("C:\\ThisKeyowrd.pdf");
        pdfHandler.GeneratePDF("Hello World!");
    }
}
class Program
{
    static void Main(string [] args)
    {
        PDFHandler pdfHandler = new PDFHandler("C:\\ThisKeyowrd.pdf");
        pdfHandler.GeneratePDF("Hello World!");
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim pdfHandler As New PDFHandler("C:\ThisKeyowrd.pdf")
		pdfHandler.GeneratePDF("Hello World!")
	End Sub
End Class
$vbLabelText   $csharpLabel

在这里,this使代码更易读且易于理解,特别是在处理像IronPDF这样的库时。

C# This(开发人员如何使用)图 1

结论

到现在,您应该已经对C#中的this关键字有了很好的理解,包括其广泛用途,从简单的实例变量到复杂的上下文,例如构造函数、扩展方法、属性、委托、匿名方法,甚至在使用像IronPDF这样流行的库时。

请记住,IronPDF 提供IronPDF 免费试用,因此您可以测试今天学到的所有内容。 如果您决定继续使用,许可证起价仅为 \$liteLicense。 IronPDF 可以成为您 C# 开发工具包中值得一用的工具,简化在应用程序中处理 PDF 文件的任务。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
C# 新手指南(开发人员如何使用)
下一步 >
C# 列表 (开发人员如何使用)