繁体   English   中英

Essentials C#Framework 3.5示例代码中的书错误

[英]Essentials C# framework 3.5 book errors in example code

我正在阅读Mark Michaelis撰写的.NET Framework 3.5 Essentials C#3.0一书。 由于涉及的课程更多,我希望有人能读完本书,也许遇到同样的问题。

第7章中的代码失败(第300页)。 清单7.2显示了如何集成接口,我已经按照书中的说明编写了所有代码。 我收到错误:

'xxxx.ConsoleListControl.DisplayHeader(string [])':并非所有代码路径都返回值。

有问题的代码是:

    public static void List(string[] headers, Ilistable[] items)
    {
        int[] columnWidths = DisplayHeaders(headers);

        for (int count = 0; count < items.Length; count++)
        {
            string[] values = items[count].ColumnValues;
            DisplayItemsRow(columnWidths, values);
        }
    }

    /// <summary>
    /// Displays the column headers
    /// </summary>
    /// <returns>returns an array of column widths</returns>
    private static int[] DisplayHeaders(string[] headers)
    {

    }

    private static void DisplayItemsRow(int[] columnWidths,string[] values)
    {

    }
}

string[]标头填充有4个项目(名字,姓氏,地址,电话)。 我不知道是什么引起了这个问题,或者如何解决它。 我看到DisplayHeaders没有值,并且columnwidths也没有值。

我还没有把所有代码都放在这里; 有5个类和1个接口。 我认为这可能太多了,不需要了。 如果有人想要所有代码,我将很乐意将其放在此处。

翻页,或重新阅读。 我猜你应该在方法中编写代码,因为它有一个返回类型但没有return语句。

编辑:好了,下载了PDF,书上面明确说明了这段代码:

考虑另一个例子

在代码中它说:

private static int[] DisplayHeaders(string[] headers)
{
    // ...
}

// ...部分表示为简洁起见,省略了对于正在解释的概念不感兴趣的内容。

代码显示为解释接口可以做什么(在这种情况下打印实现Ilistable的任何类型的对象的列表),静态帮助器方法与此无关。 代码不打算运行。

具有非void类型的任何方法都必须返回该类型的对象。 因此DisplayHeaders必须返回一个整数数组。

private static int[] DisplayHeaders(string[] headers)

private - access modifier; 表示只能从类中调用此方法

static - static modifier; 此方法不需要调用实例

int[] - 返回类型; 这是此方法将返回的对象的类型

DisplayHeaders - 方法名称; 这就是你如何引用这种方法

(string[] headers) - 参数; 这表明您需要将哪些参数传递给方法

我们可以从方法摘要中推断出它的实现看起来像这样:

    /// <summary>
    /// Displays the column headers
    /// </summary>
    /// <returns>returns an array of column widths</returns>
    private static int[] DisplayHeaders(string[] headers)
    {
        // builds a new int array with the same 
        // number of elements as the string array parameter
        int[] widths = new int[headers.Length];

        for (int i = 0; i < headers.Length; i++)
        {
            Console.WriteLine(headers[i]); // displays each header in the Console
            widths[i] = headers[i].Length; // populates the array with the string sizes
        }

        // the return keyword instructs the program to send the variable 
        // that follows back to the code that called this method
        return widths; 
    }

我会继续阅读这一章。 作者很有可能稍后会填写该方法的实现细节。

方法DisplayHeaders说它返回一个整数数组( int[] )但实际上并没有返回任何东西。 稍后很有可能代码会填充该方法以执行一些有用的操作,但是为了使代码编译,它需要返回一个数组。 一种简单的方法是将其更改为

private static int[] DisplayHeaders(string[] headers)
{
    return new int[0];
}

这会导致它返回一个空的整数数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM