c# - 将 2 个变量链接到一个对象

标签 c# class jagged-arrays

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/

相关文章:

java - 如何使用同名字符串引用类

c# - 通过 for 循环初始化带有 Lists<int> 的交错数组

c# - 什么是锯齿状数组?

c++ - 如何同时处理一个 C++ 类的多个成员?

c++ - 将对象指针 vector 传递给类 (C++)

C# 锯齿状数组 : compiler cannot implicitly convert type 'char[]' to 'int[]' . 为什么?

c# - WCF wsHttpBinding 'algorithmSuite' 无法解析错误

c# - 列表和只读属性

c# - 使用 tcp 套接字异步发送/接收固定数量的数据

c# - 用于 ajax 的 ASP.NET MVC4 Controller 的 ActionMethod 的正确路径