练习

(1)下面两个函数都存在错误,请指出这些错误。

  1. static bool Write()
  2. {
  3. Console.WriteLine("Text output from function.");
  4. }
  5. static void MyFunction(string label, params int[] args, bool showLabel)
  6. {
  7. if (showLabel)
  8. Console.WriteLine(label);
  9. foreach (int i in args)
  10. Console.WriteLine("{0}", i);
  11. }
答案: 第一个函数的返回类型是bool,但不返回一个bool值。 第二个函数有一个params实参,但这个实参不在实参列表的末尾处。

(2)编写一个应用程序,该程序使用两个命令行参数,分别把值放在一个字符串和一个整型变量中,然后显示这些值。

答案:

  1. static void Main(string[] args)
    {
    if(args.Length != 2)
    {
    Console.WriteLine("Two arguments required.");
    return;
    }
    string param1 = args[0];
    int param2 = Convert.ToInt32(args[1]);
    Console.WriteLine("String parameter: {0}", param1);
    Console.WriteLine("Integer parameter: {0}", param2);
    }
    注意这个答案包含的代码检查是否提供两个实参,本题没有这个要求,但在本题中进行检查是很合理的。


(3)创建一个委托,在请求用户输入时,使用它模拟 Console.ReadLine() 函数。

答案:

  1. class Program
    {
    delegate string ReadLineDelegate();
    static void Main(string[] args)
    {
    ReadLineDelegate readLine = new ReadLineDelegate(Console.ReadLine());
    Console.WriteLine("Type a string:");
    string userInput = readLine();
    Console.WriteLine("You typed: {0}", userInput);
    }
    }


(4)修改下面的结构,使其包含一个返回订单总价格的函数。

  1. struct order
  2. {
  3. public string itemName;
  4. public int unitCount;
  5. public double unitCost;
  6. }
答案:

  1. struct order
    {
    public string itemName;
    public int unitCount;
    public double unitCost;

    public double TotalCost()
    {
    return unitCount * unitCost;
    }
    }


(5)在 order 结构中添加另一个函数,使其返回如下所示的一个格式化的字符串(一行文本,以合适的值替换用尖括号括起来的斜体条目)。

  1. Order Information: <unit count> <item name> items at $<unit cost> each,
  2. total cost $<total cost>
答案:

  1. struct order
    {
    public string itemName;
    public int unitCount;
    public double unitCost;

    public double TotalCost()
    {
    return unitCount * unitCost;
    }

    public string Info()
    {
    return "Order information: " + unitCount.ToString() + " " + itemName +
    " items at $" + unitCost.ToString() + " each, total cost $" +
    TotalCost().ToString();
    }
    }