对C#class vs struct的误解

Misunderstanding of C# class vs struct

我试图基于 Python 示例实现自动微分 C# 库,但我对 lambda / local 函数有疑问(有点模糊,不确定为什么它不起作用)。 我什至用另一种语言实现了这个东西:Kotlin 成功地......所以我可能对某些编程部分有误解,要么是与窄/深复制或 lambda/本地函数相关的东西。

public static Value operator +(Value a, Value b)
{
    var ret = new Value(a.Data + b.Data, new[]{a, b});

    void B()
    {
        a.Gradient += ret.Gradient;
        b.Gradient += ret.Gradient;
    }

    ret._backward = B;
    return ret;
}

我给出了一小段代码,但最好看一下整体:full code with tests in 3 languages

Gradient变化不奇怪,不知道怎么解释才好。

尝试将 Valuestruct 更改为 value type to class i.e. reference type:

public class Value
{
    ...
}

如文档所述:

A variable of a value type contains an instance of the type. This differs from a variable of a reference type, which contains a reference to an instance of the type. By default, on assignment, passing an argument to a method, and returning a method result, variable values are copied. In the case of value-type variables, the corresponding type instances are copied

因此在 operator + 函数内更改局部 ab 的字段不会影响外部的值。