Skip to content

ZH TW CSharp Keyword operator

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: operator

使用手冊C# · 實用指南

指定自訂類型支援的操作行為。參數的數量和靜態/實例形式取決於操作符。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
var sum = new Count(2) + new Count(3);
System.Console.WriteLine(sum.Value);
readonly record struct Count(int Value)
{
    public static Count operator +(Count a, Count b) => new(a.Value + b.Value);
}

結果:

5

句法

public static Type operator +(Type left, Type right) => ...;

複合賦值運算子作為實例成員和實例 ++/-- 加到 C# 14。 ==/!= 和對應的比較需要正確的成對聲明。

例1:基本形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Amount total = new Amount(2) + new Amount(3);
        Console.WriteLine(total.Value);
    }
}
public readonly record struct Amount(int Value) { public static Amount operator +(Amount left, Amount right) => new(left.Value + right.Value); }

例2:另一種實用形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Counter value = new();
        value += 5; value++;
        Console.WriteLine(value.Value);
    }
}
public class Counter { public int Value { get; private set; } public void operator +=(int amount) { Value += amount; } public void operator ++() { Value++; } }

範例3

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Flag value = new(true);
        if (value) Console.WriteLine("Enabled");
    }
}
public readonly record struct Flag(bool Enabled) { public static bool operator true(Flag value) => value.Enabled; public static bool operator false(Flag value) => !value.Enabled; }

官方來源:Microsoft學習。

Clone this wiki locally