Zum Fußzeileninhalt springen
.NET HILFE

C# Aktion (Funktionsweise für Entwickler)

In this tutorial, we'll teach the concepts of C# Action, Func delegate, and related topics. This guide is designed for beginners and will walk you through the basics, provide examples, and explain key terms of action delegate.

Let's begin by understanding what delegates are in C#. We'll explore the IronPDF library later in the article.

Understanding Delegates in C#

Delegates are a programming construct that acts as references to methods, defined by a particular set of parameters and a return type, encapsulating functionalities like predefined delegate type and allowing methods to return values.

It allows the passing of methods as arguments. Essentially, a delegate serves as a function pointer, pointing to the method it represents. In C#, there are two predefined delegate types that are widely used: Func and Action.

What is a Func Delegate?

The Func delegate represents a method that can have a return value. The last type parameter specifies the return type, and the preceding types specify the input parameters.

For instance, a Func<int, int, string> takes two integer parameters and returns a string message.

Delegates in Practice: Examples

Let's take a look at some examples to understand how Func and Action delegates work in C#.

Example of an Action Delegate

An Action delegate, a predefined delegate type, is used when you want to execute a method that does not specifically return a value, focusing instead on operations. Here's a basic example:

Action<string> display = message => Console.WriteLine(message);
display("Hello, World!");
Action<string> display = message => Console.WriteLine(message);
display("Hello, World!");
Dim display As Action(Of String) = Sub(message) Console.WriteLine(message)
display("Hello, World!")
$vbLabelText   $csharpLabel

This code defines an Action delegate, illustrating the use of an anonymous method, that takes a single string parameter and prints it to the console. The => symbol is used to define a lambda expression, which is a concise way to write anonymous methods.

Example of a Func Delegate

A Func delegate, which returns a value, can be used as follows:

Func<int, int, int> add = (x, y) => x + y;
int result = add(5, 3);
Console.WriteLine(result);
Func<int, int, int> add = (x, y) => x + y;
int result = add(5, 3);
Console.WriteLine(result);
Dim add As Func(Of Integer, Integer, Integer) = Function(x, y) x + y
Dim result As Integer = add(5, 3)
Console.WriteLine(result)
$vbLabelText   $csharpLabel

This example creates a Func delegate that takes two integer parameters and returns their sum. The sum will show on the console like this:

C# Action (How It Works For Developers): Figure 1

Key Concepts

Anonymous Methods

Anonymous methods in C# provide a way to define inline methods without a name. They are often used with delegates to create delegate instances directly.

Lambda Expressions

Lambda expressions are a shorthand for writing anonymous methods. They allow you to write less code while achieving the same result.

Generic Delegate

A generic delegate can work with any data type. Func and Action are examples of generic delegates, providing more flexibility by allowing you to specify input and output types at runtime.

Delegate Instance

A delegate instance is created with the new keyword or by simply assigning a method that matches the delegate's signature.

System Namespace

The System namespace in .NET contains built-in types like Func and Action, which are part of the base class library.

Asynchronous Programming with Delegates

Delegates, including Action and Func, are integral to managing asynchronous tasks in C#. They allow developers to encapsulate a reference to a method that can then be executed asynchronously. This means that the main application thread can initiate a task and then continue with other work until the task is completed.

At that point, a callback method, referenced by a delegate, is called to handle the result. This pattern is vital for creating responsive user interfaces that remain interactive even when performing long-running operations.

Example: Asynchronous File Processing

Consider an application that needs to process a large file. Using an Action delegate in conjunction with asynchronous programming patterns like Task can significantly enhance application performance:

public async Task ProcessFileAsync(string filePath, Action<string> onComplete)
{
    // Asynchronously read file content
    string fileContent = await File.ReadAllTextAsync(filePath);
    // Process the file content here (omitted for brevity)

    // Once processing is complete, invoke the onComplete callback
    onComplete?.Invoke("File processing completed successfully.");
}
public async Task ProcessFileAsync(string filePath, Action<string> onComplete)
{
    // Asynchronously read file content
    string fileContent = await File.ReadAllTextAsync(filePath);
    // Process the file content here (omitted for brevity)

    // Once processing is complete, invoke the onComplete callback
    onComplete?.Invoke("File processing completed successfully.");
}
Public Async Function ProcessFileAsync(ByVal filePath As String, ByVal onComplete As Action(Of String)) As Task
	' Asynchronously read file content
	Dim fileContent As String = Await File.ReadAllTextAsync(filePath)
	' Process the file content here (omitted for brevity)

	' Once processing is complete, invoke the onComplete callback
	If onComplete IsNot Nothing Then
		onComplete.Invoke("File processing completed successfully.")
	End If
End Function
$vbLabelText   $csharpLabel

In this example, File.ReadAllTextAsync is used to read the file content without blocking the main thread. Once the file is processed, an Action delegate named onComplete is invoked to notify the caller that the operation is complete, allowing for further actions like updating the UI or logging results.

Introduction of IronPDF: A C# PDF Library

IronPDF is a comprehensive C# PDF library designed for .NET developers to create, edit, and manipulate PDF files with ease. It distinguishes itself with a Chrome-based rendering engine, ensuring pixel-perfect PDFs from HTML content, CSS, JavaScript, and images.

IronPDF is compatible with a wide range of .NET frameworks and environments, including .NET Standard, .NET Framework, and .NET Core, across Windows, Linux, and macOS platforms.

Installing IronPDF

To incorporate IronPDF into your .NET projects, you can use NuGet, which is the most straightforward method. Just open the Package Manager Console in Visual Studio and run the following command:

Install-Package IronPdf

This command fetches and installs the IronPDF package, setting up your project to start using IronPDF for PDF generation and manipulation.

Code Example with Action Delegate

Here's a simple example demonstrating how to use IronPDF in conjunction with an Action delegate to perform a PDF generation task:

using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // Define an Action delegate that takes HTML content as a string
        Action<string> generatePdf = html =>
        {
            // Render the HTML as a PDF
            var pdf = renderer.RenderHtmlAsPdf(html);

            // Save the PDF to a file
            pdf.SaveAs("example.pdf");
        };

        // Generate the PDF with the provided HTML
        generatePdf("<p>Hello, world!</p>");
        Console.WriteLine("PDF generated successfully.");
    }
}
using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // Define an Action delegate that takes HTML content as a string
        Action<string> generatePdf = html =>
        {
            // Render the HTML as a PDF
            var pdf = renderer.RenderHtmlAsPdf(html);

            // Save the PDF to a file
            pdf.SaveAs("example.pdf");
        };

        // Generate the PDF with the provided HTML
        generatePdf("<p>Hello, world!</p>");
        Console.WriteLine("PDF generated successfully.");
    }
}
Imports IronPdf
Imports System

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' Define an Action delegate that takes HTML content as a string
		Dim generatePdf As Action(Of String) = Sub(html)
			' Render the HTML as a PDF
			Dim pdf = renderer.RenderHtmlAsPdf(html)

			' Save the PDF to a file
			pdf.SaveAs("example.pdf")
		End Sub

		' Generate the PDF with the provided HTML
		generatePdf("<p>Hello, world!</p>")
		Console.WriteLine("PDF generated successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

This example defines an Action delegate that takes a string of HTML and uses IronPDF to render it into a PDF document. The generated PDF is then saved to the file system. This approach demonstrates how delegates can be used to encapsulate PDF generation logic, making your code more modular and flexible.

C# Action (How It Works For Developers): Figure 2

Licensing

C# Action (How It Works For Developers): Figure 3

IronPDF offers various licensing options for developers, starting from individual developer licenses to enterprise agreements. Pricing for these licenses starts from $799.

Conclusion

By now, you should have a basic understanding of Action and Func delegates in C#, along with how to use anonymous methods and lambda expressions. Remember, practice is key to mastering delegate concepts. Try creating your own examples to define, assign, and invoke delegates.

You can explore IronPDF's capabilities freely with its free trial version. Should it suit your project requirements, you can secure a license with prices commencing at $799.

Häufig gestellte Fragen

Was ist ein C# Action-Delegat?

Ein Action-Delegat in C# ist ein vordefinierter Delegattyp, der verwendet wird, um eine Methode auszuführen, die keinen Wert zurückgibt. Er wird häufig für Operationen verwendet, bei denen kein Ergebnis zurückgegeben werden muss.

Wie kann ich einen Func-Delegat in C# verwenden?

Ein Func-Delegat wird verwendet, um eine Methode zu kapseln, die einen Wert zurückgibt. Sie geben den Rückgabetyp als letzten Parameter an. Er ist nützlich für Methoden, bei denen Sie ein berechnetes Ergebnis zurückgeben müssen.

Was ist der Unterschied zwischen Func- und Action-Delegaten?

Der Hauptunterschied besteht darin, dass ein Func-Delegat einen Wert zurückgibt, während ein Action-Delegat das nicht tut. Func wird verwendet, wenn die Methode ein Ergebnis zurückgeben muss, während Action für Prozeduren ohne Rückgabewert ist.

Wie kann ich ein PDF in einer C#-Anwendung erstellen?

Sie können ein PDF in einer C#-Anwendung mit IronPDF erstellen. Es ermöglicht Ihnen, PDFs mit einem Chrome-basierten Rendering-Engine zu generieren und kann in .NET-Anwendungen unter Verwendung von Delegaten integriert werden.

Was sind Lambda-Ausdrücke in C# und wie hängen sie mit Delegaten zusammen?

Lambda-Ausdrücke sind eine knappe Möglichkeit, Inline-Methoden zu schreiben, die häufig mit Delegaten verwendet werden, um den Code zu vereinfachen. Sie ermöglichen es Ihnen, Methoden prägnant auszudrücken und werden häufig mit Action- und Func-Delegaten verwendet.

Wie kann ich asynchrone Aufgaben in C# mit Delegaten handhaben?

Delegaten wie Action und Func können verwendet werden, um Methoden zu kapseln, die asynchron ausgeführt werden. Dieser Ansatz ermöglicht Ihrer Anwendung, andere Operationen auszuführen, während sie auf die Fertigstellung von Aufgaben wartet, um die Leistung und Reaktionsfähigkeit zu verbessern.

Wie installiert man eine C#-Bibliothek zur PDF-Erstellung in einem .NET-Projekt?

Um eine Bibliothek wie IronPDF in Ihrem .NET-Projekt zu installieren, verwenden Sie NuGet in der Paket-Manager-Konsole mit dem Befehl: Install-Package IronPdf. Dies bereitet Ihr Projekt für die Erstellung und Bearbeitung von PDFs vor.

Was sind anonyme Methoden in C#?

Anonyme Methoden ermöglichen es Ihnen, Inline-Methoden ohne einen Namen zu definieren, häufig mit Delegaten, um Delegatinstanzen direkt zu erstellen. Sie bieten eine Möglichkeit, Codeblöcke als Parameter zu übergeben.

Was ist ein generischer Delegat in C#?

Generische Delegaten sind Delegaten, die jeden Datentyp verwenden können. Func und Action sind Beispiele für generische Delegaten, da sie es Ihnen ermöglichen, die Typen der Eingabe- und Ausgabeparameter zur Laufzeit zu definieren.

Was ist der System-Namespace in .NET und seine Bedeutung?

Der System-Namespace in .NET enthält wesentliche Typen und Klassen wie Func und Action, die Teil der Basisklassenbibliothek sind und Kernfunktionen für die Entwicklung von C#-Anwendungen bereitstellen.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen