.NET 幫助

C# 運算符(如何對開發者起作用)

發佈 2024年3月6日
分享:

在 C# 中,運算子在對變數和數值執行各種操作方面扮演著至關重要的角色。無論您是初學者還是經驗豐富的開發人員,牢固掌握 C# 運算子 對於撰寫高效且表達力強的代碼來說,操作符是基本的。在本綜合指南中,我們將探討 C# 中不同類型的操作符及其在程式中的使用方式。我們還將了解如何將這些 C# 操作符與 IronPDF.

在C#中的運算子類型

1.1. 算術運算子

C# 中的算術運算子用於基本的數學運算。這些運算包括加法 (+),減法 (-), 乘法 (*),分區 (/)和模數 (%). 對於算術運算子,運算子的優先順序類似於數學運算子優先順序中常見的 BEDMAS 或 PEDMAS。

讓我們深入探討一個範例,以了解這些運算子的工作方式:

// Arithmetic Operators
        int a = 10;
        int b = 3;
        int sum = a + b;
        int difference = a - b;
        int product = a * b;
        int quotient = a / b;
        int remainder = a % b;
        Console.WriteLine($"Arithmetic Operators:");
        Console.WriteLine($"Sum: {sum}, Difference: {difference}, Product: {product}, Quotient: {quotient}, Remainder: {remainder}");
        Console.WriteLine();
// Arithmetic Operators
        int a = 10;
        int b = 3;
        int sum = a + b;
        int difference = a - b;
        int product = a * b;
        int quotient = a / b;
        int remainder = a % b;
        Console.WriteLine($"Arithmetic Operators:");
        Console.WriteLine($"Sum: {sum}, Difference: {difference}, Product: {product}, Quotient: {quotient}, Remainder: {remainder}");
        Console.WriteLine();
' Arithmetic Operators
		Dim a As Integer = 10
		Dim b As Integer = 3
		Dim sum As Integer = a + b
		Dim difference As Integer = a - b
		Dim product As Integer = a * b
		Dim quotient As Integer = a \ b
		Dim remainder As Integer = a Mod b
		Console.WriteLine($"Arithmetic Operators:")
		Console.WriteLine($"Sum: {sum}, Difference: {difference}, Product: {product}, Quotient: {quotient}, Remainder: {remainder}")
		Console.WriteLine()
VB   C#

1.2. 關係運算子

關係運算子用於比較數值並確定它們之間的關係。C# 中常見的關係運算子包括大於 (請提供您要翻譯的內容。)小於 (<),等於 (==),不等於 (!= )大於或等於 (>=),且小於或等於 (<=).

// Relational Operators
        bool isEqual = (a == b);
        bool notEqual = (a != b);
        bool greaterThan = (a > b); // true if the left operand is greater than the right
        bool lessThan = (a < b); // true if the left operand is less than the right
        bool greaterOrEqual = (a >= b);
        bool lessOrEqual = (a <= b);
        Console.WriteLine($"Relational Operators:");
        Console.WriteLine($"Equal: {isEqual}, Not Equal: {notEqual}, Greater Than: {greaterThan}, Less Than: {lessThan}, Greater or Equal: {greaterOrEqual}, Less or Equal: {lessOrEqual}");
        Console.WriteLine();
// Relational Operators
        bool isEqual = (a == b);
        bool notEqual = (a != b);
        bool greaterThan = (a > b); // true if the left operand is greater than the right
        bool lessThan = (a < b); // true if the left operand is less than the right
        bool greaterOrEqual = (a >= b);
        bool lessOrEqual = (a <= b);
        Console.WriteLine($"Relational Operators:");
        Console.WriteLine($"Equal: {isEqual}, Not Equal: {notEqual}, Greater Than: {greaterThan}, Less Than: {lessThan}, Greater or Equal: {greaterOrEqual}, Less or Equal: {lessOrEqual}");
        Console.WriteLine();
' Relational Operators
		Dim isEqual As Boolean = (a = b)
		Dim notEqual As Boolean = (a <> b)
		Dim greaterThan As Boolean = (a > b) ' true if the left operand is greater than the right
		Dim lessThan As Boolean = (a < b) ' true if the left operand is less than the right
		Dim greaterOrEqual As Boolean = (a >= b)
		Dim lessOrEqual As Boolean = (a <= b)
		Console.WriteLine($"Relational Operators:")
		Console.WriteLine($"Equal: {isEqual}, Not Equal: {notEqual}, Greater Than: {greaterThan}, Less Than: {lessThan}, Greater or Equal: {greaterOrEqual}, Less or Equal: {lessOrEqual}")
		Console.WriteLine()
VB   C#

1.3. 邏輯運算子

邏輯運算子用於對布林值進行邏輯運算。在 C# 中常見的邏輯運算是 AND (&&),或 (**

),並且不是 (!**)AND 和 OR 是有兩個操作數的二元運算符,而 NOT 是一元運算符,這意味著它只影響一個操作數。

// Logical Operators
        bool condition1 = true;
        bool condition2 = false;
        bool resultAnd = condition1 && condition2;
        bool resultOr = condition1 
 condition2;
        bool resultNot = !condition1;
        Console.WriteLine($"Logical Operators:");
        Console.WriteLine($"AND: {resultAnd}, OR: {resultOr}, NOT: {resultNot}");
        Console.WriteLine();
// Logical Operators
        bool condition1 = true;
        bool condition2 = false;
        bool resultAnd = condition1 && condition2;
        bool resultOr = condition1 
 condition2;
        bool resultNot = !condition1;
        Console.WriteLine($"Logical Operators:");
        Console.WriteLine($"AND: {resultAnd}, OR: {resultOr}, NOT: {resultNot}");
        Console.WriteLine();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

1.4. 賦值運算符

賦值運算符用於給變量賦值。簡單的賦值運算符是 =。然而,C# 也提供了複合賦值運算符,如 +=-=、*=/=%=

// Assignment Operators
        int x = 5;
        int y = 2;
        x += y; // Equivalent to x = x + y
        y *= 3; // Equivalent to y = y * 3
        Console.WriteLine($"Assignment Operators:");
        Console.WriteLine($"x after +=: {x}, y after *=: {y}");
        Console.WriteLine();
// Assignment Operators
        int x = 5;
        int y = 2;
        x += y; // Equivalent to x = x + y
        y *= 3; // Equivalent to y = y * 3
        Console.WriteLine($"Assignment Operators:");
        Console.WriteLine($"x after +=: {x}, y after *=: {y}");
        Console.WriteLine();
' Assignment Operators
		Dim x As Integer = 5
		Dim y As Integer = 2
		x += y ' Equivalent to x = x + y
		y *= 3 ' Equivalent to y = y * 3
		Console.WriteLine($"Assignment Operators:")
		Console.WriteLine($"x after +=: {x}, y after *=: {y}")
		Console.WriteLine()
VB   C#

1.5. 位运算符

位运算符在二进制位层面进行操作。它们包括位运算符:按位与 (&), 按位或 ( )位元 XOR (^)比特位非或比特補码(~),左移 (<<)以及右移 (>>).

// Bitwise Operators
        int p = 5; // Binary: 0101
        int q = 3; // Binary: 0011
        int bitwiseAnd = p & q;
        int bitwiseOr = p 
 q;
        int bitwiseXor = p ^ q;
        int bitwiseNotP = ~p;
        int leftShift = p << 1;
        int rightShift = p >> 1;
        Console.WriteLine($"Bitwise Operators:");
        Console.WriteLine($"AND: {bitwiseAnd}, OR: {bitwiseOr}, XOR: {bitwiseXor}, NOT: {bitwiseNotP}, Left Shift: {leftShift}, Right Shift: {rightShift}");
        Console.WriteLine();
// Bitwise Operators
        int p = 5; // Binary: 0101
        int q = 3; // Binary: 0011
        int bitwiseAnd = p & q;
        int bitwiseOr = p 
 q;
        int bitwiseXor = p ^ q;
        int bitwiseNotP = ~p;
        int leftShift = p << 1;
        int rightShift = p >> 1;
        Console.WriteLine($"Bitwise Operators:");
        Console.WriteLine($"AND: {bitwiseAnd}, OR: {bitwiseOr}, XOR: {bitwiseXor}, NOT: {bitwiseNotP}, Left Shift: {leftShift}, Right Shift: {rightShift}");
        Console.WriteLine();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

1.6. 條件運算子 (三元運算子)

條件運算子 (?:) 是一種在單行中表達if-else語句的簡寫方式。

// Conditional (Ternary) Operator
    int age = 20;
    string result = (age >= 18) ? "Adult" : "Minor";
    Console.WriteLine($"Conditional Operator:");
    Console.WriteLine($"Result: {result}");
    Console.WriteLine();
// Conditional (Ternary) Operator
    int age = 20;
    string result = (age >= 18) ? "Adult" : "Minor";
    Console.WriteLine($"Conditional Operator:");
    Console.WriteLine($"Result: {result}");
    Console.WriteLine();
' Conditional (Ternary) Operator
	Dim age As Integer = 20
	Dim result As String = If(age >= 18, "Adult", "Minor")
	Console.WriteLine($"Conditional Operator:")
	Console.WriteLine($"Result: {result}")
	Console.WriteLine()
VB   C#

在此範例中,如果 age 大於或等於 18,則 result 的值將為 "Adult",否則為 "Minor"。

1.7. Null-Coalescing Operator

1.7. 空合併運算符

空合併運算符 (??) 用於為可空類型提供預設值。

// Null-Coalescing Operator
        int? nullableValue = null;
        int resultCoalesce = nullableValue ?? 10;
        Console.WriteLine($"Null-Coalescing Operator:");
        Console.WriteLine($"Result: {resultCoalesce}");
// Null-Coalescing Operator
        int? nullableValue = null;
        int resultCoalesce = nullableValue ?? 10;
        Console.WriteLine($"Null-Coalescing Operator:");
        Console.WriteLine($"Result: {resultCoalesce}");
' Null-Coalescing Operator
		Dim nullableValue? As Integer = Nothing
		Dim resultCoalesce As Integer = If(nullableValue, 10)
		Console.WriteLine($"Null-Coalescing Operator:")
		Console.WriteLine($"Result: {resultCoalesce}")
VB   C#

1.8 輸出所有 C# 運算子代碼範例的螢幕截圖

C# 運算子 (對開發人員的運作方式):圖 1 - 所有運算子輸出。

2. 介紹 IronPDF

IronPDF IronPDF for C# 是一個多功能的程式庫,能幫助開發者無縫整合PDF相關功能到他們的 .NET 應用程式中。IronPDF 提供了一套全面的工具,方便用戶創建、修改及提取 PDF 文件中的資訊。無論是從 HTML 生成動態 PDF、從網站抓取內容,還是進行高級格式設定,IronPDF 都能以直觀的 API 簡化這些流程。

IronPDF 被廣泛應用於需要 PDF 操作的應用程式中,例如報告生成和文件管理系統,IronPDF 簡化了複雜的任務,成為使用 C# 和 .NET 技術的開發者的重要資源。請隨時參閱官方文件以獲取精確的使用說明和更新。

2.1. 開始使用 IronPDF

要在您的 C# 專案中開始使用 IronPDF,您首先需要安裝 IronPDF NuGet 套件您可以通過在套件管理器控制台中輸入以下命令來完成此操作:

Install-Package IronPdf

或者,您可以使用 NuGet 套件管理器搜尋「IronPDF」並從那裡安裝套件。

一旦安裝完套件,您就可以開始使用 IronPDF 無縫地處理 PDF 文件。

2.2. 代碼範例:使用 C# 運算符搭配 IronPDF

using IronPdf;
using System;
class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();
        // Add content with mathematical operations
        string content = $@"<!DOCTYPE html>
                            <html>
                            <body>
                                <h1>Mathematical Operations in IronPDF</h1>
                                <p>Sum: 5 + 7 = {5 + 7}</p>
                                <p>Product: 3 * 4 = {3 * 4}</p>
                                <p>Division: 10 / 2 = {10 / 2}</p>
                                <p>Modulus: 15 % 4 = {15 % 4}</p>
                            </body>
                            </html>";
        // Render HTML content to PDF
        var pdf = renderer.RenderHtmlAsPdf(content);
        // Save the PDF to a file
        pdf.SaveAs("MathOperations.pdf");
        Console.WriteLine("PDF with mathematical operations created successfully!");
    }
}
using IronPdf;
using System;
class Program
{
    static void Main()
    {
        var renderer = new ChromePdfRenderer();
        // Add content with mathematical operations
        string content = $@"<!DOCTYPE html>
                            <html>
                            <body>
                                <h1>Mathematical Operations in IronPDF</h1>
                                <p>Sum: 5 + 7 = {5 + 7}</p>
                                <p>Product: 3 * 4 = {3 * 4}</p>
                                <p>Division: 10 / 2 = {10 / 2}</p>
                                <p>Modulus: 15 % 4 = {15 % 4}</p>
                            </body>
                            </html>";
        // Render HTML content to PDF
        var pdf = renderer.RenderHtmlAsPdf(content);
        // Save the PDF to a file
        pdf.SaveAs("MathOperations.pdf");
        Console.WriteLine("PDF with mathematical operations created successfully!");
    }
}
Imports IronPdf
Imports System
Friend Class Program
	Shared Sub Main()
		Dim renderer = New ChromePdfRenderer()
		' Add content with mathematical operations
		Dim content As String = $"<!DOCTYPE html>
                            <html>
                            <body>
                                <h1>Mathematical Operations in IronPDF</h1>
                                <p>Sum: 5 + 7 = {5 + 7}</p>
                                <p>Product: 3 * 4 = {3 * 4}</p>
                                <p>Division: 10 / 2 = {10 \ 2}</p>
                                <p>Modulus: 15 % 4 = {15 Mod 4}</p>
                            </body>
                            </html>"
		' Render HTML content to PDF
		Dim pdf = renderer.RenderHtmlAsPdf(content)
		' Save the PDF to a file
		pdf.SaveAs("MathOperations.pdf")
		Console.WriteLine("PDF with mathematical operations created successfully!")
	End Sub
End Class
VB   C#

此 C# 代码利用 IronPDF 库創建了一個 PDF 文件,其中包含我們展示的多個運算符。它使用 ChromePdfRenderer 類來呈現 HTML 內容,其中包含使用 C# 運算符計算的數學表達式。

HTML 內容包含顯示結果(如總和、乘積、除法和模數)的標題和段落,這些內容通過字符串格式化進行插值。 渲染的 HTML 然後通過 IronPDF 轉換為 PDF,生成的 PDF 保存為 “MathOperations.pdf”。

C# 運算子(開發人員如何使用):圖 2 - 來自前述代码的輸出 PDF 文件

3. 結論

掌握C#運算子對開發者來說是至關重要的,這使得他們在算術、關係、邏輯、賦值、位元、條件以及空合併操作中能夠進行高效的編碼。本全面指南探討了各種運算子類型,並提供了實用的代碼範例。此外,介紹了IronPDF,突顯了其在C#中的Excel相關任務中的實用性。

通過無縫地將C#運算子與 IronPDF,開發人員可以在 PDF 檔案中輕鬆進行算術運算,展示此函式庫的多功能性。總的來說,對 C# 運算子的扎實理解可以使開發人員創建更強大且表達能力更強的代碼,適用於各種程式任務。

您可以造訪這個網站獲取 IronPDF 的免費試用許可證 連結. 了解更多關於 IronPDF 請訪問 這裡以及範例程式碼,請參閱 這裡.

< 上一頁
C# OAuth2(開發人員如何使用)
下一個 >
C# Nameof(它如何為開發者工作)

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

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