1. if 语句:
int age = 25;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are a minor.");
}
2. else if 语句:
int score = 75;
if (score >= 90)
{
Console.WriteLine("Excellent!");
}
else if (score >= 70)
{
Console.WriteLine("Good job!");
}
else
{
Console.WriteLine("You can do better.");
}
3. switch 语句:
int dayOfWeek = 3;
string dayName;
switch (dayOfWeek)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
// 其他情况...
default:
dayName = "Invalid day";
break;
}
Console.WriteLine($"The day is {dayName}");
4. 三元运算符:
int number = 42;
string result = (number > 0) ? "Positive" : "Non-positive";
5. 空值合并运算符:
string name = null;
string result = name ?? "Default Name";
6. 为 null 判断:
string name = null;
if (name == null)
{
Console.WriteLine("Name is null.");
}
else
{
Console.WriteLine($"Name is {name}");
}
7. 使用 is 运算符进行类型判断:
object obj = "Hello, C#";
if (obj is string)
{
string text = (string)obj;
Console.WriteLine(text);
}
以上是一些基本的 C# 判断结构和运算符。通过合理使用这些结构,您可以根据不同的条件执行不同的代码块,实现更灵活的程序逻辑。
转载请注明出处:http://www.zyzy.cn/article/detail/14749/C#