2011-09-05 13 views
0

好吧,我正在做我的實驗室從C#類涉及使用參數參數,數組和方法。我在做這件事時遇到了一些問題,我正在尋求幫助。所以..首先我將問題修改爲最簡單的塊,以幫助我解釋我遇到的問題。下面是一段簡單的代碼:需要幫助使用REF和數組,方法

using System; 

public class Repository 
{ 
    string[] titles; 

    static void Main(string[] args) 
    { 
     string title; 

     Console.Write("Title of book: "); 
     title = Console.ReadLine(); 

     getBookInfo(ref title); 
    } 

    static void getBookInfo(ref string title) 
    { 
     titles[0] = title; 
    } 

    static void displayBooks(string[] titles) 
    { 
     Console.WriteLine("{0}", titles[0]); 
    } 
} 

現在,U將嘗試編譯代碼,您會發現無法編譯,因爲錯誤說「對象引用才能訪問非靜態成員「庫。冠軍」。問題在於3種方法的格式必須與作業中所述的完全相同。現在,如何在保留此模板的同時避免此問題?

其他問題,我將如何顯示方法displayBooks的內容在主? (由於問題,我沒有這麼遠)。

問候,請幫助!

-----------------------謝謝你的幫助! ---------

+0

我真的會接近你的講師/老師,他爲什麼使用'ref',他知道他在說什麼嗎? –

+0

我當然希望他能做到:D – HelpNeeder

回答

1

首先,除非你想改變它的title的價值,你不需要使用ref存在於Main()之內。以下代碼演示了這一概念:

static void Main(string[] args) 
{ 
    string a = "Are you going to try and change this?"; 
    string b = "Are you going to try and change this?"; 

    UsesRefParameter(ref a); 
    DoesntUseRefParameter(b); 
    Console.WriteLine(a); // I changed the value! 
    Console.WriteLine(b); // Are you going to try and change this? 
} 

static void UsesRefParameter(ref string value) 
{ 
    value = "I changed the value!"; 
} 

static void DoesntUseRefParameter(string value) 
{ 
    value = "I changed the value!"; 
} 

需要先創建一個數組,然後才能使用它。因此,這裏是你的代碼已經被更正:

static string[] titles; 

static void Main(string[] args) 
{ 
    string title; 
    titles = new string[1]; // We can hold one value. 

    Console.Write("Title of book: "); 
    title = Console.ReadLine(); 

    getBookInfo(title); 
} 

static void getBookInfo(string title) 
{ 
    titles[0] = title; 
} 

要顯示你的書,你可以試試下面的方法:

static void displayBooks(string[] titles) 
{ 
    // Go over each value. 
    foreach (string title in titles) 
    { 
     // And write it out. 
     Console.WriteLine(title); 
    } 
} 
// In Main() 
displayBooks(titles); 
+0

超級!讓我試試這個。很有用! – HelpNeeder

1

關於第一個問題,讓titles靜:

private static string[] titles; 
1

好吧,首先你要分配所有權的指數0一個名稱尚未初始化的標題數組。從本質上講,它是一個空數組,當你試圖給它賦值的時候。

快速的方法來滿足這個問題是修改這樣的代碼:

private static string[] titles; 

    static void Main(string[] args) 
    { 

     string title; 

     Console.Write("Title of book: "); 
     title = Console.ReadLine(); 

     getBookInfo(ref title); 
     displayBooks(titles); 
    } 

    static void getBookInfo(ref string title) 
    { 
     //titles[0] = title; 
     titles = new string[] {title}; 
    } 

    static void displayBooks(string[] titles) 
    { 
     Console.WriteLine("{0}", titles[0]); 
    } 

如果你想要更多的書籍分配給這個數組並打印出來,你需要初始化大小的數組。我只會使用一個List<string>,它可以添加到沒有定義初始大小。

要設置標題數組的大小簡單地做到這一點:static string[] titles = new string[50];

去了一下這個計劃打算做,有更多的邏輯需要添加。比如一個計數器變量,爲titles數組中的下一個索引添加一個標題。