介绍C语言的控制语句

220 阅读5分钟

软件需要一种方法,在它通过代码的执行取得进展时作出决定。这就是控制流发挥作用的地方。程序控制流是通过使用控制语句提供给我们的。这些是C#语言中的特殊关键字,允许程序员在执行过程中设置诸如分支、循环,甚至整个跳转到程序的新点。让我们来看看这些关键字和结构,如if、switch、do while、for、foreach、while、break、return和其他一些。


C#的 if语句

通过在程序中使用if 语句,开发人员可以根据某个条件做出决定。想象一下,来到一个岔路口。你会选择哪条路?在你的头脑中,你可能会评估一些条件。如果我向左走,那么我将按时到达目的地。如果我往右走,风景会更好。所以你决定像任何理性的人一样向右走。C#中的if 语句允许我们在代码中做这种类型的事情。if语句根据一个布尔表达式的值选择一个分支来执行。这是一种华丽的说法,如果某件事是真的,就做这个,否则就做那个。下面是C#代码中的一个例子。

bool condition = true;

if (condition)
{
    Console.WriteLine("condition is true.");
}
else
{
    Console.WriteLine("condition is false.");
}

这里是if语句的另一个例子,它表明有时你不必包括大括号。

if (age <= 2)
    StayHome();

else if (age < 18)
    GoToSchool();

else
{
    GoToWork();
}

我们可以看到在上面的片段中,没有用大括号来包围对StayHome()的调用。然而,在大多数情况下,使用大括号被认为是一种好的编码风格,因为它使代码更容易维护,也更易读。只有当只有一行代码需要评估时,你才能省略大括号。如果你需要执行一个以上的语句,大括号总是需要的。因此,当设置一个代码块,或多行代码时,要用大括号包围。如果你不这样做,那么只有if语句后的第一行会被执行。如果if语句中的第一个表达式返回错误,比方说年龄是17岁,那么StayHome()就不会被调用。程序将跳到下一个if语句来评估该语句。如果该语句为真,就调用GoToSchool()。如果第一个和第二个if语句都是假的,你就去工作()。


嵌套if语句

如果你愿意,你可以嵌套if语句。在下面的代码中,只有当两个条件都为真时,程序才会写出 "该商品正在销售"。 if条件都为真。在将几个语句嵌套在一起时,你应该注意 if语句时要注意,因为代码会变得难以阅读。

if (currentprice <= 9.99 )
{
    if (regularprice == 15.99)
    {
        Console.WriteLine("The item is on sale.");
    }
}

C# 三元操作符

你可以使用的一个非常方便的控制语句是三元运算符,在C#中称为条件运算符。它有三个部分。

csharp ternary conditional operator
第一部分是一个表达式,需要返回。如果表达式返回,我们将返回冒号左边的第二部分的值。否则,我们将返回冒号右侧的第3部分的值。这个条件运算符非常适用于快速条件检查,为一个变量分配两个不同的值之一。这是你最经常看到的使用方式。同样的逻辑也可以用if语句来完成,但是用三元运算符的话,需要输入的字符就少了。最好将其用于简单的逻辑检查。如果你把一些复杂的逻辑放在条件运算符的范围内,事情会变得难以阅读。


分支

让我们在我们的项目中尝试一些分支。我们要做的是为StockStatistics类添加一种方法来确定股票组合的整体估值。下面是我们将如何设置的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stocks
{
    public class StockStatistics
    {
        public StockStatistics()
        {
            HighestStock = 0;
            LowestStock = float.MaxValue;
        }

        public string StockValuation
        {
            get
            {
                string result;
                if (AverageStock >= 200)
                {
                    result = "Very Expensive";
                }
                else if (AverageStock >= 150)
                {
                    result = "Expensive";
                }
                else if (AverageStock >= 100)
                {
                    result = "Average";
                }
                else if (AverageStock >= 50)
                {
                    result = "Good Value";
                }
                else
                {
                    result = "Very Good Value";
                }
                return result;
            }
        }

        public float AverageStock;
        public float HighestStock;
        public float LowestStock;
    }
}

我们在这里做的是查看投资组合中的平均股价,以了解目前事情是否具有良好的价值,或者是昂贵到非常昂贵。我们可以通过修改Program.cs中的几处内容将其添加到我们的程序输出中。在这里,我们想增加这个额外的输出,为我们提供关于整体估值的信息。要做到这一点,我们还需要为CustomWriteLine()添加一个重载方法,该方法需要两个字符串参数。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stocks
{
    class Program
    {
        static void Main(string[] args)
        {
            StockPortfolio portfolio = new StockPortfolio();

            portfolio.PortfolioNameChanged += OnPortfolioNameChanged;

            portfolio.Name = "'Warren Buffet Portfolio'";
            portfolio.Name = "'Bootleg Capital'";

            portfolio.AddStock(55.81f);
            portfolio.AddStock(74.52f);
            portfolio.AddStock(152.11f);
            portfolio.AddStock(199.85f);
            portfolio.AddStock(225.28f);

            StockStatistics stats = portfolio.ComputeStatistics();
            Console.WriteLine("The Current Name Is: " + portfolio.Name + "n");
            CustomWriteLine("The Average Stock Price Is: ", stats.AverageStock);
            CustomWriteLine("The Highest Stock Price Is: ", stats.HighestStock);
            CustomWriteLine("The Lowest Stock Price Is: ", stats.LowestStock);
            CustomWriteLine("Overall Valuation: ", stats.StockValuation);
        }

        static void OnPortfolioNameChanged(object sender, PortfolioNameChangedEventArgs args)
        {
            Console.WriteLine($"Portfolio name changed from {args.oldName} to {args.newName}! n");
        }

        static void CustomWriteLine(string description, float result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }

        static void CustomWriteLine(string description, string result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }
    }
}

现在,当我们运行程序时,我们会得到这个额外的输出,正如我们在这里看到的。
start without debugging output


C# 开关语句

在C#中,我们也有一个 **switch**语句。它可以用来将程序的执行分支到一个case标签内的一组语句,这个标签是用关键字 case.C#的switch语句通过将switch内部的值与你在每个case标签中指定的值进行匹配来实现这一目的。

  • 被限制在整数、字符、字符串和枚举中
  • 案例标签是常数
  • 默认标签是可选的

有了这些知识,我们想给StockStatistic类设置一个推荐功能。我们将使用一个开关语句来帮助我们完成这个任务。这个开关语句要做的是查看我们刚刚创建的StockValuation属性。它是一个字符串值。对于每一种情况,我们都会查看字符串值是否匹配,如果匹配,则提供相关的建议。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stocks
{
    public class StockStatistics
    {
        public StockStatistics()
        {
            HighestStock = 0;
            LowestStock = float.MaxValue;
        }

        public string StockValuation
        {
            get
            {
                string result;
                if (AverageStock >= 200)
                {
                    result = "Very Expensive";
                }
                else if (AverageStock >= 150)
                {
                    result = "Expensive";
                }
                else if (AverageStock >= 100)
                {
                    result = "Average";
                }
                else if (AverageStock >= 50)
                {
                    result = "Good Value";
                }
                else
                {
                    result = "Very Good Value";
                }
                return result;
            }
        }

        public string Recommendation
        {
            get
            {
                string result;
                switch (StockValuation)
                {
                    case "Very Expensive":
                        result = "Take profits.";
                        break;
                    case "Expensive":
                        result = "Sell some, hold some.";
                        break;
                    case "Average":
                        result = "Continue to hold.";
                        break;
                    case "Good Value":
                        result = "Consider buying.";
                        break;
                    default:
                        result = "Buy.";
                        break;
                }
                return result;
            }
        }

        public float AverageStock;
        public float HighestStock;
        public float LowestStock;
    }
}

在Program.cs文件中,我们需要在这里添加高亮的一行代码,以在程序中添加这个额外的输出。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stocks
{
    class Program
    {
        static void Main(string[] args)
        {
            StockPortfolio portfolio = new StockPortfolio();

            portfolio.PortfolioNameChanged += OnPortfolioNameChanged;

            portfolio.Name = "'Warren Buffet Portfolio'";
            portfolio.Name = "'Bootleg Capital'";

            portfolio.AddStock(55.81f);
            portfolio.AddStock(74.52f);
            portfolio.AddStock(152.11f);
            portfolio.AddStock(199.85f);
            portfolio.AddStock(225.28f);

            StockStatistics stats = portfolio.ComputeStatistics();
            Console.WriteLine("The Current Name Is: " + portfolio.Name + "n");
            CustomWriteLine("The Average Stock Price Is: ", stats.AverageStock);
            CustomWriteLine("The Highest Stock Price Is: ", stats.HighestStock);
            CustomWriteLine("The Lowest Stock Price Is: ", stats.LowestStock);
            CustomWriteLine("Overall Valuation: ", stats.StockValuation);
            CustomWriteLine("Current Recommendation: ", stats.Recommendation);
        }

        static void OnPortfolioNameChanged(object sender, PortfolioNameChangedEventArgs args)
        {
            Console.WriteLine($"Portfolio name changed from {args.oldName} to {args.newName}! n");
        }

        static void CustomWriteLine(string description, float result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }

        static void CustomWriteLine(string description, string result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }
    }
}

我们可以在这里看到这个新输出的结果。
c sharp switch example output
switch语句对于评估范围来说不是很好,但对于替代if / else / if语句来说有时很有用。


在C#中进行迭代

迭代也被称为循环。循环是指当你需要或想要多次执行一段代码的时候。要在C#中进行迭代,你可以使用 for, while, do while、 、 或 **foreach**构造。


C# for

for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}
0
1
2
3
4
5
6
7
8
9

C# while

int n = 0;
while (n < 7)
{
    Console.WriteLine(n);
    n++;
}
0
1
2
3
4
5
6

C# do while

int n = 0;
do 
{
    Console.WriteLine(n);
    n++;
} while (n < 3);
0
1
2

C# foreach

var numbers = new List<int> { 0, 5, 10, 15, 20, 25, 30, 35 };
int count = 0;
foreach (int element in numbers)
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");
Element #1: 0
Element #2: 5
Element #3: 10
Element #4: 15
Element #5: 20
Element #6: 25
Element #7: 30
Element #8: 35
Number of elements: 8

我们也可以在我们的示例程序中练习一些迭代结构。让我们添加一个功能,列出所有已经添加到程序中的股票价格。首先,在Program.cs中,我们将添加这个突出的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stocks
{
    class Program
    {
        static void Main(string[] args)
        {
            StockPortfolio portfolio = new StockPortfolio();

            portfolio.PortfolioNameChanged += OnPortfolioNameChanged;

            portfolio.Name = "'Warren Buffet Portfolio'";
            portfolio.Name = "'Bootleg Capital'";

            portfolio.AddStock(55.81f);
            portfolio.AddStock(74.52f);
            portfolio.AddStock(152.11f);
            portfolio.AddStock(199.85f);
            portfolio.AddStock(225.28f);
            portfolio.ListStocks(Console.Out);

            StockStatistics stats = portfolio.ComputeStatistics();
            Console.WriteLine("The Current Name Is: " + portfolio.Name + "n");
            CustomWriteLine("The Average Stock Price Is: ", stats.AverageStock);
            CustomWriteLine("The Highest Stock Price Is: ", stats.HighestStock);
            CustomWriteLine("The Lowest Stock Price Is: ", stats.LowestStock);
            CustomWriteLine("Overall Valuation: ", stats.StockValuation);
            CustomWriteLine("Current Recommendation: ", stats.Recommendation);
        }

        static void OnPortfolioNameChanged(object sender, PortfolioNameChangedEventArgs args)
        {
            Console.WriteLine($"Portfolio name changed from {args.oldName} to {args.newName}! n");
        }

        static void CustomWriteLine(string description, float result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }

        static void CustomWriteLine(string description, string result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }
    }
}

然后,在StockPortolio.cs中,我们需要实现这个方法。它利用了.net中的TextWriter类型,并在程序中的股票集合上循环。当它在每个股票上循环时,它将把它写到控制台。

using System;
using System.Collections.Generic;
using System.IO;

namespace Stocks
{
    public class StockPortfolio
    {
        public StockPortfolio()
        {
            _name = "'Starting Name'";
            stocks = new List<float>();
        }

        public StockStatistics ComputeStatistics()
        {
            StockStatistics stats = new StockStatistics();

            float sum = 0;
            foreach (float stock in stocks)
            {
                stats.HighestStock = Math.Max(stock, stats.HighestStock);
                stats.LowestStock = Math.Min(stock, stats.LowestStock);
                sum += stock;
            }

            stats.AverageStock = sum / stocks.Count;
            return stats;
        }

        public void ListStocks(TextWriter destination)
        {
            Console.WriteLine("The list of stock prices is");
            for (int i = 0; i < stocks.Count; i++)
            {
                destination.WriteLine(stocks[i]);
            }
            Console.WriteLine("n");
        }

        public void AddStock(float stock)
        {
            stocks.Add(stock);
        }

        public string Name
        {
            get { return _name; }
            set
            {
                if (!String.IsNullOrEmpty(value))
                {
                    if (_name != value)
                    {
                        PortfolioNameChangedEventArgs args = new PortfolioNameChangedEventArgs();
                        args.oldName = _name;
                        args.newName = value;
                        PortfolioNameChanged(this, args);
                    }
                    _name = value;
                }
            }
        }

        public event PortfolioNameChangedDelegate PortfolioNameChanged;

        private string _name;
        private List<float> stocks;
    }
}

现在,我们看到了我们的迭代结果的作用
c sharp iterating with for loop


在C#中跳转

在C#中,你可以通过使用以下关键词之一跳转到程序中的一个特定点。

  • Break
  • 继续
  • 跳转
  • 返回

我们看到, break是与 case语句中的 switch语句中与标签一起使用。它也可以用在一个 while, do while, for或一个 foreach循环内使用,以脱离并停止循环。


C#的break

停止它所出现的最接近的封闭式循环或开关语句。

for (int i = 1; i <= 50; i++)
{
    if (i == 7)
    {
        break;
    }
    Console.WriteLine(i);
}
1
2
3
4
5
6

C# continue

将控制权传递给它所出现的while、do、for或foreach循环的下一个迭代。

for (int i = 1; i <= 5; i++)
{
    if (i < 4)
    {
        continue;
    }
    Console.WriteLine(i);
}
4
5

C# goto

将控制权直接转移到程序中的一个标记点。

int[] nums = new int[] { 1, 2, 3, 4, 5 };
foreach (int num in nums)
{
    if (num == 3)
    {
        goto target;
    }
    Console.WriteLine(num);
}
target:
Console.WriteLine("Stopping at 3!");
1
2
Stopping at 3!

C# return

停止执行它所出现的方法,并将控制权送回调用代码。通常会返回一个值,但不一定非得如此。

static int One()
{
    // This method returns an integer.
    return 100;
}

static string Two()
{
    // This method returns a string.
    return "Hi There!";
}

static int Three(int num1, int num2)
{
    // This method returns an integer based on an expression.
    return (num1 * 10) + num2;
}

static void Four()
{
    // This method uses a return statement with no expression (void).
    Console.WriteLine("Four executed");
    return;
}

C#控制语句总结

在本教程中,我们介绍了C#编程语言中可供我们使用的各种类型的流程控制语句。控制语句大致可分为执行分支的语句、用于循环的语句和用于跳转的语句。分支语句包括if、else if、条件运算符和switch语句。当我们需要对事物进行迭代,或进行循环时,我们就看for、while、do while和foreach语句。最后,我们简单看了一下跳转结构,如break、continue、goto和return。