Layers 是一个交错的 Node 数组,每个节点作为 source[] 和 destination[] 表示 Theta 数组。
问题是,为什么当我更改第四行的代码时,链接这些对象后第五行仍然打印“0”?
theta t = new theta();
layers[1][i].source[j] = t;
layers[0][j].destination[i] = t;
layers[0][j].destination[i].weight = 5;
Console.WriteLine(layers[1][i].source[j].weight);
struct theta
{
public double weight;
public theta(double _weight) { weight = _weight; }
}
class node
{
public theta[] source;
public theta[] destination;
public double activation;
public double delta;
public node() { }
public node(double x) { activation = x; }
}
图层填充方式示例:
node n = new node();
n.destination = new theta[numberOfNodesPerHiddenLayer+1];
n.source = new theta[numberOfNodesPerHiddenLayer+1];
layers[i][j] = n;
最佳答案
这是因为 Theta 是一个结构,而不是类。结构被隐式复制。当你在做的时候:
theta t = new theta();
layers[1][i].source[j] = t;
layers[0][j].destination[i] = t;
您最终得到了“t”的三个副本。一份原件,一份在索引 1,i 和一份在索引 0,j。然后,您仅将 5 分配给其中一个副本。所有其他保持不变。这就是结构与类的不同之处:它们是通过值复制分配的,而不是通过引用分配的。
关于c# - 将 2 个变量链接到一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16511073/