簡體   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