🧠 一、C# 运算符列表(按类别分类)
类别 | 运算符 |
---|---|
一元运算符 | + , - , ++ , -- , ! , ~ , (T) x |
算术运算符 | + , - , * , / , % |
赋值运算符 | = , += , -= , *= , /= , %= , &= , ` |
比较/关系运算符 | == , != , < , > , <= , >= |
逻辑/布尔运算符 | && , ` |
按位运算符 | & , ` |
条件运算符 | ?: (三元) |
空相关运算符 | ?? , ??= , ?. , ?[] |
Lambda 表达式 | => |
对象创建 | new |
访问运算符 | . , [] , () , -> (用于指针) |
类型信息 | typeof , is , as |
范围与索引 | ^ , .. |
✅ 二、详细讲解 + 示例代码
1. 一元运算符(Unary Operators)
csharp
int a = 5;
int b = -a; // 负号
bool flag = true;
Console.WriteLine(!flag); // false
2. 增减运算符(Increment / Decrement)
csharp
int x = 5;
Console.WriteLine(x++); // 输出 5,之后 x=6
Console.WriteLine(++x); // 输出 7,先加再输出
3. 强制转换运算符(Cast Operator)
csharp
double d = 9.99;
int i = (int)d; // 显式转换,结果为 9
4. 求反运算符(Logical NOT 和 Bitwise NOT)
csharp
bool isTrue = true;
Console.WriteLine(!isTrue); // false
byte b = 0b1010_1010;
Console.WriteLine(~b); // 按位取反
5. 赋值运算符(Assignment Operators)
csharp
int num = 10;
num += 5; // 等价于 num = num + 5 → 15
6. 字符串连接运算符(Concatenation)
csharp
string greeting = "Hello" + ", World!";
7. 算术运算符(Arithmetic Operators)
csharp
int sum = 10 + 5;
int remainder = 10 % 3; // 余数 1
8. 布尔逻辑运算符(Logical Operators)
csharp
bool result1 = true && false; // false
bool result2 = true || false; // true
9. 关系运算符(Relational Operators)
csharp
int age = 20;
Console.WriteLine(age > 18); // true
10. 按位运算符(Bitwise Operators)
csharp
int x = 5; // 0b0101
int y = 3; // 0b0011
int z = x & y; // 按位与:0b0001 → 1
11. 复合赋值运算符(Compound Assignment)
csharp
int total = 100;
total -= 20; // total = 80
12. new 运算符(创建对象)
csharp
List<string> list = new List<string>();
Person p = new Person { Name = "Tom" };
13. 访问运算符(Member Access)
csharp
person.Name
array[index]
14. 索引和范围运算符(Index and Range)
csharp
string s = "HelloWorld";
char c = s[^1]; // 最后一个字符 'd'
string sub = s[6..^0]; // 从索引6开始到最后:"World"
15. 类型信息(Type Information)
csharp
Console.WriteLine(typeof(string)); // System.String
object obj = 123;
if (obj is int) Console.WriteLine("是整数");
16. 运算符优先级(Operator Precedence)
优先级 | 运算符 |
---|---|
高 | x.y , f(x) , a[i] , new , typeof |
中 | ! , ~ , ++x , --x , (T)x |
中 | * , / , % |
中 | + , - |
中 | << , >> |
中 | < , > , <= , >= |
中 | == , != |
中 | & |
中 | ^ |
中 | ` |
中 | && |
中 | ` |
低 | ?: |
低 | = , op= |
✅ 使用括号
()
可以改变优先级顺序。
17. 关联规则(Associativity)
- 大多数运算符是左结合 ,如
a + b + c
- 但赋值运算符是右结合 :
a = b = c
等价于a = (b = c)
- 三元运算符也是右结合
18. 空条件运算符(Null-Conditional Operators)
csharp
string name = person?.Name; // 如果 person 为 null,则返回 null
int? length = person?.Name?.Length;
19. 空值合并运算符(Null Coalescing Operator)
csharp
string message = null;
string result = message ?? "默认消息"; // 如果 message 为 null,用默认值
20. 空折叠赋值运算符(Null-Coalescing Assignment)
csharp
string text = null;
text ??= "初始值"; // text 为 null,所以赋值
21. 三元运算符(Ternary Conditional Operator)
csharp
int max = a > b ? a : b;
string result = score >= 60 ? "及格" : "不及格";
22. Lambda 运算符(Lambda Expression)
csharp
Func<int, int> square = x => x * x;
list.Where(x => x > 10);
🧮 三、实战练习:计算素数(Prime Numbers)
csharp
using System;
class Program
{
static void Main()
{
Console.Write("请输入一个正整数:");
string input = Console.ReadLine();
if (int.TryParse(input, out int n) && n > 1)
{
bool isPrime = true;
for (int i = 2; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
isPrime = false;
break;
}
}
Console.WriteLine($"{n} 是{(isPrime ? "质数" : "非质数")}");
}
else
{
Console.WriteLine("输入无效,请输入大于 1 的整数!");
}
}
}
🎯 项目名称:C# 运算符综合练习器
功能说明:
这个程序会引导用户输入数据,并演示以下内容:
- 基本算术、逻辑、关系、位运算
- 空值处理(
??
,?.
,??=
) - 三元条件运算符
- Lambda 表达式
- 类型转换与类型检查
- 索引与范围操作
- 创建对象(
new
)
✅ 完整代码模板(Program.cs)
csharp
using System;
class Program
{
// 自定义类用于测试 new 和访问运算符
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return $"Name: {Name}, Age: {Age}";
}
}
static void Main()
{
Console.WriteLine("=== C# 运算符综合练习 ===\n");
// 1. 算术运算符
int a = 20, b = 7;
Console.WriteLine($"加法: {a} + {b} = {a + b}");
Console.WriteLine($"取模: {a} % {b} = {a % b}");
// 2. 一元运算符
int c = 5;
Console.WriteLine($"\n前置自增: ++{c} = {++c}");
Console.WriteLine($"后置自减: {c}-- = {c--}");
// 3. 关系运算符
Console.WriteLine($"\n{a} > {b} ? {a > b}");
Console.WriteLine($"{a} == {b} ? {a == b}");
// 4. 逻辑运算符
bool flag1 = true, flag2 = false;
Console.WriteLine($"\nflag1 && flag2 ? {flag1 && flag2}");
Console.WriteLine($"!flag2 ? {!flag2}");
// 5. 按位运算符
byte x = 0b1010_1010;
Console.WriteLine($"\n按位取反 ~x = {Convert.ToString(~x, 2)}");
Console.WriteLine($"x << 1 = {x << 1}");
// 6. 三元运算符
string result = (a > b) ? "a 大于 b" : "a 不大于 b";
Console.WriteLine($"\n三元判断结果: {result}");
// 7. 空值相关运算符
string str1 = null;
string str2 = "默认文本";
Console.WriteLine($"\n空合并 ?? : {str1 ?? str2}");
str1 ??= "首次赋值";
Console.WriteLine($"空折叠赋值 ??= : {str1}");
Person person = null;
Console.WriteLine($"安全访问 ?. : {person?.ToString() ?? "person 为 null"}");
// 8. 类型信息和强制转换
object obj = 123;
if (obj is int)
{
int num = (int)obj;
Console.WriteLine($"\n强制转换 (int)obj → {num}");
}
// 9. 范围和索引
string text = "HelloWorld";
Console.WriteLine($"\n字符串索引 ^1: {text[^1]}");
Console.WriteLine($"子串范围 ..^5: {text[..^5]}");
// 10. Lambda 表达式
Func<int, int> square = x => x * x;
Console.WriteLine($"\nLambda 计算平方: square(5) = {square(5)}");
// 11. new 运算符
Person p = new Person { Name = "Alice", Age = 25 };
Console.WriteLine($"\nnew 创建对象: {p}");
Console.WriteLine("\n按任意键退出...");
Console.ReadKey();
}
}
📋 示例运行输出:
=== C# 运算符综合练习 ===
加法: 20 + 7 = 27
取模: 20 % 7 = 6
前置自增: ++5 = 6
后置自减: 6-- = 6
20 > 7 ? True
20 == 7 ? False
flag1 && flag2 ? False
!flag2 ? True
按位取反 ~x = 1111111111111111111111111010101 (取决于平台)
x << 1 = 170
三元判断结果: a 大于 b
空合并 ?? : 默认文本
空折叠赋值 ??= : 首次赋值
安全访问 ?. : person 为 null
强制转换 (int)obj → 123
字符串索引 ^1: d
子串范围 ..^5: Hello
Lambda 计算平方: square(5) = 25
new 创建对象: Name: Alice, Age: 25
按任意键退出...