我无法设置线程数组对象watek [i]的Name方法的字符串值。视觉抛出异常:“ System.NullReferenceException:'对象引用未设置为对象的实例。'“
int watki;
string watki2;
Console.WriteLine("Ile watkow uruchomic?: ");
watki2 = Console.ReadLine();
watki = Convert.ToInt32(watki2);
Thread[] watek = new Thread[watki];
for (int i = 0; i < watki; i++)
{
watek[i].Name = Convert.ToString(i);
watek[i] = new Thread(() => Program.Watek(watek[i].Name, watki));
}
我的问题是:它甚至可能吗?如果是的话,我在做什么错了?
答案 0 :(得分:0)
尝试一下。
在实例化该对象之前,不能在该对象上分配属性。
for (int i = 0; i < watki; i++)
{
watek[i] = new Thread(() => Program.Watek(Convert.ToString(i), watki));
}
答案 1 :(得分:0)
使用对象初始化:
for (int i = 0; i < watki; i++)
{
string name = i.ToString();
watek[i] = new Thread(() => Program.Watek(name, watki)) { Name = name };
}