【问题标题】:Linking 2 variables to one object将 2 个变量链接到一个对象
【发布时间】:2013-05-06 20:08:00
【问题描述】:

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数组是如何填充的。
  • 请发布整个外部/嵌套循环(如果适用)代码 sn-p 因为不清楚索引 i 和 j 的来源。 Rgds,
  • 将结构更改为类,一切都会正常工作。就目前的用途而言,在那里有结构是没有意义的
  • 层在其每个维度上单独实例化。这是关于如何填充层(节点数组)的代码示例:node n = new node();n.destination = new theta[numberOfNodesPerHiddenLayer+1];n.source = new theta[numberOfNodesPerHiddenLayer+1];layers[i][j] = n;

标签: c# class jagged-arrays


【解决方案1】:

这是因为struct 是一个值类型(相对于一个引用类型)并且具有值类型的复制语义。例如,请参阅此帖子:What is the difference between a reference type and value type in c#? 了解更多信息。

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

【讨论】:

    【解决方案2】:

    这是因为 Theta 是一个 STRUCT,而不是类。结构被隐式复制。当你在做:

    theta t = new theta();
    layers[1][i].source[j] = t;
    layers[0][j].destination[i] = t;
    

    您最终会得到三个“t”副本。一份原件,一份在索引 1,i 和一份在索引 0,j。然后,您仅将 5 分配给其中一个副本。所有其他保持不变。这就是结构与类的不同之处:它们是通过值复制而不是通过引用来分配的。

    【讨论】:

    • 谢谢!您的解决方案完美运行!我认为struct 只是另一个类,但有一些限制,例如为简化起见没有函数/程序。我应该多看书! D:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2019-02-22
    • 2023-02-04
    • 1970-01-01
    • 2016-11-25
    • 2013-01-10
    相关资源
    最近更新 更多