這裏就不設置到對象的NullReferenceException是未處理的C#誤差(類和對象)
這裏的一個實例的錯誤 對象引用是我的問題:我有內CD 2類,宋,CD是一個數組當我嘗試訪問歌曲數組來設置或獲取屬性時,我會得到一個錯誤。
這裏是我的CD類:
public class CD
{
private string cdtitle;
private string artist;
public Song[] songList = new Song[10];
private int releasedate;
//constructors
public CD()
{
cdtitle = artist = "";
releasedate = 2014;
numCDs = 0;
}
public CD(string t, string a)
{
cdtitle = t;
artist = a;
numCDs = 0;
}
//Properties
public string CDTitle
{
get
{
return cdtitle;
}
set
{
cdtitle = value;
}
}
public string CDArtist
{
get
{
return artist;
}
set
{
artist = value;
}
}
public int ReleaseDate
{
get
{
return releasedate;
}
set
{
releasedate = value;
}
}
}
這裏是歌曲類
public class Song
{ //attributes
private string songtitle;
private int songlength; //seconds
//constructors
//default constructor
public Song()
{
songtitle = "";
songlength = 0;
}
//initialize the song title only
public Song(string st)
{
songtitle = st;
songlength = 0;
}
//initialize the length only
public Song(int len)
{
songtitle = "";
songlength = len;
}
//Properties
public string SongTitle
{
get
{
return songtitle;
}
set
{
songtitle = value;
}
}
public int SongLength
{
get
{
return songlength;
}
set
{
songlength = value;
}
}
}
每當我試圖從我的CD訪問對象的SongList我得到一個NullReferenceException錯誤 對象引用未設置爲一個對象的實例
private void addSongToolStripMenuItem_Click(object sender, EventArgs e)
{
string tempTitle;
int tempLength = 0;
CD myCD = new CD();
frmAddSong newSong = new frmAddSong();
newSong.ShowDialog();
tempLength = Convert.ToInt32(newSong.txtSongLength.Text);
tempTitle = newSong.txtSongTitle.Text;
//index is a form level variable
myCD.songList[index].SongLength = tempLength;// I get the error here
myCD.songList[index].SongTitle = tempTitle;// or here
MessageBox.Show(tempTitle + " " + tempLength.ToString());//Confirmation
index++;
}
幾乎所有NullReferenceException異常是相同的。你試圖訪問一個空對象的屬性(這是因爲你的歌曲列表中沒有歌曲在某個索引處)。最好的方法是設置一個斷點並調試程序,以瞭解爲什麼輸入爲空並糾正錯誤。 –
在訪問它之前,您需要在'myCD.songList [index]'創建一個新的'Song'對象。 – swandog