2012-07-04 11 views
0

作爲c#的新手,我不明白變量是如何在對象之間傳遞的。當我執行這個程序時,我的數組變量「filePaths」會返回null。這是一個基本的窗體。我正在製作一個能夠顯示文字並播放聲音的程序。C#訪問跨不同對象的變量

特定的錯誤是「的NullReferenceException是未處理。

這裏是我的特殊代碼。

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.IO; 
using System.Media; 

namespace Kindersect 
{ 
public partial class form1 : Form 
{ 
    string[] filePaths; 
    string directpath = "C:\\Users\\Optimus Prime\\Documents\\vocabaudio\\"; 
    int counter = 0; 
    int c = 0; 
    public form1() 
    { 
     InitializeComponent(); 
    } 

    public void button1_Click(object sender, EventArgs e) 
    { 
     timer1.Enabled = true; 
     string[] filePaths = Directory.GetFiles(directpath, "*.wav"); 
     foreach(string k in filePaths) 
     { 
      c++; 
     } 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     if (counter < c) 
     { 
      label1.Text = filePaths[counter]; 
      SoundPlayer simpleSound = new SoundPlayer(filePaths[counter]); 
      simpleSound.Play(); 
      counter++; 
     } 

    } 
} 

}

在此先感謝。

+1

正在使用您的計算機擎天柱嗎?那是個很酷的男人。 – DarthVader

+0

感謝大家解釋我所擁有的聲明問題以及我所遇到的角色轉義問題。我的新鮮感背叛了我。 –

+0

你叫'noob' – DarthVader

回答

3

您聲明兩個不同的變量......在不同的範圍

刪除的String []從文件路徑的第二個聲明,如果你想進入全球申報文件路徑

+0

謝謝你的答案是有效的,併爲我的理解說明。我現在正在接受我的下一個錯誤... –

2

引用時失去@的你的變量。

你還聲明filePaths兩次。一旦進入類(並且從未定義),並且一旦進入按鈕單擊事件處理程序,該處理程序將不在該方法的作用域中。你只想在類中聲明它並在方法中設置它,所以從方法的行中刪除string[]

+0

好吧,它沒有幫助,但肯定。任何關於讓按鈕點擊創建的值在計時器下可讀的想法? –

0

第一:你不應該開始定時器設置變量之前。二:你不必重新定義變量的類型(如果在開始時定義的話)。

0

我可以在你的代碼中看到的問題是declare string [] filePaths;然後在timer1_Tick Event中使用它,但在string [] filePaths中使用它;因爲在button1_Click中有一個類似的名稱變量,所以永遠不會爲其賦值:string [] filePaths = Directory.GetFiles(@directpath,「* .wav」);但這個文件路徑陣列的範圍僅僅是內部的button1_Click只有

So to resolve your issue please change 

string[] filePaths = Directory.GetFiles(@directpath, "*.wav"); 

to 

filePaths = Directory.GetFiles(@directpath, "*.wav"); 

我建議你用你的方法這種方法更小和清晰的代碼用更少的變量:

public void button1_Click(object sender, EventArgs e) 
{ 
    timer1.Enabled = true; 
} 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     filePaths = Directory.GetFiles(directpath, "*.wav"); 
     if (counter < filePaths.Length) 
     { 
      label1.Text = filePaths[counter]; 
      SoundPlayer simpleSound = new SoundPlayer(filePaths[counter]); 
      simpleSound.Play(); 
      counter++; 
     } 

    } 

如果你可以使用Form_Load事件中的Directory.GetFiles這種方式會被調用一次

0

看起來你錯誤地使用了@符號。字符串或字符串引用前面的@符號旨在禁用反斜槓的轉義功能(\)。通常情況下,您必須使用當前擁有的其他反斜槓(\\)來避免反斜槓。

所以......

string directpath = "C:\\Users\\Optimus Prime\\Documents\\vocabaudio\\"; 

相當於

string directpath = @"C:\Users\Optimus Prime\Documents\vocabaudio\"; 

參見:@(at) sign in file path/string