簡體   English   中英

C#跨不同對象訪問變量

[英]C# accessing variables across different objects

作為C#的新手,我不了解如何在對象之間傳遞變量。 執行此程序時,我的數組變量“ filePaths”返回空值。 這是基本的Windows窗體。 我正在制作一個可以顯示單詞並播放聲音的程序。

具體錯誤是“未處理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++;
        }

    }
}

}

提前致謝。

您要聲明兩個不同的變量...在不同的范圍內

如果要訪問全局聲明的文件路徑,請從第二個文件路徑聲明中刪除string []

引用變量時,請不要使用@。

您還要兩次聲明filePaths 一次在類中(並且從未定義),一次在按鈕click事件處理程序中,該事件處理程序超出該方法的范圍。 您只想在類中聲明它並在方法中進行設置,因此從方法的行中刪除string[]

首先:您不應該在設置變量之前啟動計時器。

二:如果在開頭定義了變量,則不必重新定義變量的類型。

我在您的代碼中看到的問題是聲明string [] filePaths;。 在類級別,然后在timer1_Tick事件中使用它,但使用string [] filePaths; 永遠不會獲取分配給它的值,因為在button1_Click上有一個相似的名稱變量:line [] filePaths = Directory.GetFiles(@directpath,“ * .wav”); 但是此filePaths數組的范圍僅在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,它將僅被調用一次

看來您使用的@符號不正確。 字符串或字符串引用前面的@符號用於禁用反斜杠( \\ )的轉義功能。 通常,您必須像當前使用的( \\\\ )一樣使用附加的反斜杠來轉義反斜杠。

所以...

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

相當於

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

另請參閱: @(at)登錄文件路徑/字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM