.NET 幫助

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

在 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()
$vbLabelText   $csharpLabel

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()
$vbLabelText   $csharpLabel

1.3. 邏輯運算符

邏輯運算符用於對布林值進行邏輯操作。 C# 中的常見邏輯運算是 AND (&&)、OR (**)

),而不是(!**)。 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
$vbLabelText   $csharpLabel

賦值運算子

賦值運算符用於將值賦給變量。 簡單的賦值運算符是=。 然而,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()
$vbLabelText   $csharpLabel

1.5. 位元運算子

位運算符在位級別上執行二進制運算。 它們包括位運算運算子:位元 AND(&)、位元 OR( ),按位异或(^),按位非或按位补码(~),左移(<<),右移(>>)。

// 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
$vbLabelText   $csharpLabel

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()
$vbLabelText   $csharpLabel

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

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}")
$vbLabelText   $csharpLabel

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

C# 運算子(開發人員的工作原理):圖 1 - 所有運算子輸出。

2. 介紹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
$vbLabelText   $csharpLabel

此C#代碼使用IronPDF庫來創建一個包含多個運算符的PDF文檔。 它使用 ChromePdfRenderer 類別來渲染 HTML 內容,其中包括使用 C# 運算符計算的數學表達式。

HTML 內容中包含顯示結果的標題和段落,如總和、乘積、除法和模數,透過字串格式化進行插值。 然後使用 IronPDF 將渲染的 HTML 轉換為 PDF,並將生成的 PDF 保存為「MathOperations.pdf」。

C# 運算子 (開發者如何使用): 圖 2 - 前述程式碼輸出的 PDF 文件

3. 結論

掌握 C# 運算子對開發人員來說是基礎的,這能透過算術、關係、邏輯、賦值、位元運算、條件和空合併操作實現高效編碼。 本綜合指南探討了各種操作符類型,並提供了實用的代碼示例。 此外,IronPDF 的推出強調了其在 C# 中與 Excel 相關任務的實用性。

透過將 C# 運算符與 IronPDF 無縫整合,開發人員可以輕鬆地在 PDF 文件中執行算術運算,展示了該庫的多功能性。 總體來說,對 C# 運算子的深刻理解能夠讓開發人員為各類程式設計任務創建更加強大且具表達力的程式碼。

您可以通過訪問此鏈接獲取IronPDF的免費試用許可證。 要了解更多關於IronPDF的信息,請訪問這裡,有關代碼範例請訪問這裡

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# OAuth2(開發人員如何使用)
下一個 >
C# Nameof(它如何為開發者工作)