C# 访问元素数组
好的,我做了另一个程序来更清楚地说明我的问题。我有一个包含int数组的对象数组,我正试图从元素neuronone打印索引[0]。但是,我在“Console.WriteLine(ex.neuron[0])行收到一个空引用异常 我的代码如下C# 访问元素数组,c#,C#,好的,我做了另一个程序来更清楚地说明我的问题。我有一个包含int数组的对象数组,我正试图从元素neuronone打印索引[0]。但是,我在“Console.WriteLine(ex.neuron[0])行收到一个空引用异常 我的代码如下 namespace ConsoleApplication5 { class Program { static void Main() { ex ex = new ex(); int[]neuron1 =
namespace ConsoleApplication5
{
class Program
{
static void Main()
{
ex ex = new ex();
int[]neuron1 = new int[5];
int[]neuron2 = new int[5];
int[]neuron3 = new int[5];
int[]neuron4 = new int[5];
int[]neuron5 = new int[5];
object[,] array1 = new object[2,2];
array1[0, 0] = ex.neuron1;
neuron1[0] = 1;
array1[0, 1] = neuron2;
neuron2[1] = 1;
test(array1);
}
static void test(object[,] array1)
{
ex ex = new ex();
Console.WriteLine(ex.neuron1[0]);
Console.ReadLine();
}
}
}
我在这里有一节课,学习和设置neuron1:
static void test(object[,] array1)
{
ex ex = new ex();
Console.WriteLine(ex.neuron1[0]);
Console.ReadLine();
}
}
}
我认为异常是在我访问ex.neuron[0]时发生的,因为它尚未被定义为包含值1。所以我的问题是,在is被设置为保持值1之后,如何访问ex.neuron[0]。谢谢。您从未设置ex.1,请更换这些行
int[] neuron1 = new int[5];
与
您正在每个函数中创建一个新的
ex
实例,而您可能只需要传递它。此外,您从未在实例本身上设置neuron
字段。以下是您的代码的简化版本:
static void Main()
{
// define it here
ex ex = new ex();
// initialize the neuron fields (although you should probably do this
// in the constructor for ex
ex.neuron1 = new int[5];
ex.neuron2 = new int[5];
ex.neuron3 = new int[5];
ex.neuron4 = new int[5];
ex.neuron5 = new int[5];
// set some neuron array values
ex.neuron1[0] = 1;
ex.neuron2[1] = 1;
// pass the instance along to test
test(ex);
}
static void test(ex ex)
{
// access the array value here
Console.WriteLine(ex.neuron1[0]);
Console.ReadLine();
}
前男友是你上的课吗?您声明ex=new ex();您声明了一个与类同名的变量?如何实现
ex
?@Sorceri Yes ex是我创建的一个类,并且变量的名称相同。抱歉,这只是我很快举的一个简短的例子
static void Main()
{
// define it here
ex ex = new ex();
// initialize the neuron fields (although you should probably do this
// in the constructor for ex
ex.neuron1 = new int[5];
ex.neuron2 = new int[5];
ex.neuron3 = new int[5];
ex.neuron4 = new int[5];
ex.neuron5 = new int[5];
// set some neuron array values
ex.neuron1[0] = 1;
ex.neuron2[1] = 1;
// pass the instance along to test
test(ex);
}
static void test(ex ex)
{
// access the array value here
Console.WriteLine(ex.neuron1[0]);
Console.ReadLine();
}