C# 在UserControl数组中,每个控件都有一个方法在那里设置标签的文本,但会得到一个NullReferenceException。救命啊!
因此,我创建了一个数组:C# 在UserControl数组中,每个控件都有一个方法在那里设置标签的文本,但会得到一个NullReferenceException。救命啊!,c#,collections,user-controls,for-loop,iteration,C#,Collections,User Controls,For Loop,Iteration,因此,我创建了一个数组: TorrentItem[] torrents = new TorrentItem[10]; TorrentItem控件有一个名为SetTorrentName(字符串名称)的方法: 我使用for循环填充10个TorrentItems,如下所示: private TorrentItem[] GetTorrents() { TorrentItem[] torrents = new TorrentItem[10]; string test = "";
TorrentItem[] torrents = new TorrentItem[10];
TorrentItem控件有一个名为SetTorrentName(字符串名称)的方法:
我使用for循环填充10个TorrentItems,如下所示:
private TorrentItem[] GetTorrents()
{
TorrentItem[] torrents = new TorrentItem[10];
string test = "";
for (int i = 0; i < 10; i++)
{
test = i.ToString();
TorrentItem[i].SetTorrentName(test); //I get a null reference error here.
//What am I doing wrong?
}
private TorrentItem[]GetTorrents()
{
TorrentItem[]torrents=新TorrentItem[10];
字符串测试=”;
对于(int i=0;i<10;i++)
{
测试=i.ToString();
TorrentItem[i].SetTorrentName(test);//我在这里得到一个空引用错误。
//我做错了什么?
}
您创建了对10个对象的引用数组,但不在数组中创建10个对象。所有数组元素在初始化之前均为null
for( int i = 0; i < 10; ++i )
{
torrents[i] = new TorrentItem();
/* do something with torrents[i] */
}
for(int i=0;i<10;++i)
{
torrents[i]=新的TorrentItem();
/*用激流做点什么*/
}
但是,名称初始化可能会被放入构造函数中。您创建了一个对10个对象的引用数组,但没有在数组中创建10个对象。所有数组元素在初始化之前都是
null
for( int i = 0; i < 10; ++i )
{
torrents[i] = new TorrentItem();
/* do something with torrents[i] */
}
for(int i=0;i<10;++i)
{
torrents[i]=新的TorrentItem();
/*用激流做点什么*/
}
但是,名称初始化可能会放入构造函数。您需要初始化每个单独的项目:
for (int i = 0; i < 10; i++)
{
TorrentItem[i] = new TorrentItem(); //Initialize each element of the array
test = i.ToString();
TorrentItem[i].SetTorrentName(test); //I get a null reference error here.
//What am I doing wrong?
}
for(int i=0;i<10;i++)
{
TorrentItem[i]=new TorrentItem();//初始化数组的每个元素
测试=i.ToString();
TorrentItem[i].SetTorrentName(test);//我在这里得到一个空引用错误。
//我做错了什么?
}
您需要初始化每个项目:
for (int i = 0; i < 10; i++)
{
TorrentItem[i] = new TorrentItem(); //Initialize each element of the array
test = i.ToString();
TorrentItem[i].SetTorrentName(test); //I get a null reference error here.
//What am I doing wrong?
}
for(int i=0;i<10;i++)
{
TorrentItem[i]=new TorrentItem();//初始化数组的每个元素
测试=i.ToString();
TorrentItem[i].SetTorrentName(test);//我在这里得到一个空引用错误。
//我做错了什么?
}