[英]I get an error: use of unassigned local variable 'artist', don't know what i'm doing wrong?
private void btn_AddSongArtistPlaylist_Click(object sender, EventArgs e)
{
Artist artist;
if (cmbBox_AddSongPlaylistArtist.SelectedIndex == 0)
{
if (cmbBox_Artist.SelectedIndex == 0)
{
artist = new Artist(txtBox_NameArtist.Text, dateTP_BirthdatArtist.Value.Date);
}
else
{
foreach (Artist a in Artists)
{
if (a.Name == cmbBox_Artist.SelectedText)
{
artist = a;
}
}
}
Song song = new Song(txtBox_Name.Text, Convert.ToInt32(txtBox_YearBirthday.Text), artist, txtBox_PathToFile.Text);
}
}
You are using the potentially unassigned variable artist
. 您正在使用可能未分配的变量
artist
。 See: 看到:
private void btn_AddSongArtistPlaylist_Click(object sender, EventArgs e)
{
Artist artist;
if (cmbBox_AddSongPlaylistArtist.SelectedIndex == 0)
{
if (cmbBox_Artist.SelectedIndex == 0)
{
artist = new Artist(txtBox_NameArtist.Text, dateTP_BirthdatArtist.Value.Date);
}
else
{
foreach (Artist a in Artists)
{
if (a.Name == cmbBox_Artist.SelectedText)
{
artist = a;
}
}
}
Song song = new Song(txtBox_Name.Text, Convert.ToInt32(txtBox_YearBirthday.Text), artist, txtBox_PathToFile.Text); // right here!
}
}
If the second if
statement evaluates to false
, and there are no objects in the Artists
collection, you will hit that new Song
line with an unassigned variable. 如果第二个
if
语句的计算结果为false
,并且Artists
集合中没有对象,则将使用未分配的变量命中new Song
行。 Try initializing artist
to null
. 尝试将
artist
初始化为null
。
private void btn_AddSongArtistPlaylist_Click(object sender, EventArgs e)
{
Artist artist = null;
if (cmbBox_AddSongPlaylistArtist.SelectedIndex == 0)
{
if (cmbBox_Artist.SelectedIndex == 0)
{
artist = new Artist(txtBox_NameArtist.Text, dateTP_BirthdatArtist.Value.Date);
}
else
{
foreach (Artist a in Artists)
{
if (a.Name == cmbBox_Artist.SelectedText)
{
artist = a;
}
}
}
Song song = new Song(txtBox_Name.Text, Convert.ToInt32(txtBox_YearBirthday.Text), artist, txtBox_PathToFile.Text); // now you're fine
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.