将2个变量链接到一个对象

4

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;

你应该澄清layers数组如何填充。 - Niels Keurentjes
请发布完整的外部/嵌套循环(如果适用)代码片段,因为不清楚索引i和j来自哪里。谢谢。 - Alexander Bell
将结构体改为类,一切都会正常工作。目前的使用中,保留结构体没有任何意义。 - ashcliffe
层在每个维度上都是单独实例化的。以下是关于如何填充层(节点数组)的代码示例:node n = new node();n.destination = new theta[numberOfNodesPerHiddenLayer+1];n.source = new theta[numberOfNodesPerHiddenLayer+1]; layers[i][j] = n; - Auromius
2个回答

4
这是因为Theta是一个结构体,而非类。结构体会被隐式复制。当您进行以下操作时:
theta t = new theta();
layers[1][i].source[j] = t;
layers[0][j].destination[i] = t;

在执行这段代码后,你将得到三个“t”的副本。一个原始副本,一个位于索引1的i和一个位于索引0的j。然后,你只会将5赋值给其中一个副本,其他副本都不会被修改。这就是结构体与类之间的区别:它们是通过值复制进行分配的,而不是通过引用。


谢谢!你的解决方案完美地解决了问题!我以为 struct 只是另一个类,但是有一些限制,例如没有函数/过程,只是为了简化。我应该多读书!D: - Auromius

0

这是因为struct是一个值类型(与引用类型相对),并且具有值类型的复制语义。例如,可以参考此帖子:在C#中引用类型和值类型之间的区别是什么?以获取更多信息。

如果您将theta的类型更改为class,它可能会按照您的预期工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接