3

在将一个字段分配给另一个字段时,C# 只是复制数据,还是实际创建链接?在这篇文章中有一个游戏引擎结构的例子。那里的编码器具有包含其父级的组件。在 C# 中,它们只是包含父副本,还是引用它?

示例代码:

class World
{
    ...
    public void Update()
    {
        ...
        ent.OnAttach(this);
        ...
    }
    ...
}

class Entity
{
    ...
    public void OnAttach(World world)
    {
        world_ = world;
    }
    ...
}

Entity 对象现在可以访问 World 对象并可以访问它的字段和方法,就像在文章中一样?(或者我误解了代码?)

4

4 回答 4

6

因为您的数据类型World被定义为 aclass而不是 astruct这意味着当您分配该类型的变量时,只会复制对相同数据的引用。

In other wrods, whether you then use world.SomeProperty = something or world_.someProperty = something they will be editing the same object in memory.

If you change your data type to be a struct then the entire data structure will be copied and you will have two copies of the same data.

Regardless of how you defined your data, once you have a reference to the data you can then access its methods or properties. So, yes, once your Entity object has a reference to the world object it can access any methods or properties on it (as long as they are not private).

于 2010-01-16T21:37:58.660 回答
4

这取决于World类型。如果它是引用类型(类),则复制的引用将指向同一个对象,因此更改新引用指向的对象将影响原始对象(不会创建新对象)。在发布的示例中就是这种情况。该字段将仅引用同一World对象。

如果该World类型是值类型,它会被复制(连同其内容),并将成为一个完全不同的值,更改不会影响原始值。

于 2010-01-16T21:37:29.497 回答
3

As Entity & World are class (i.e. "reference types"), then they would just have references to each other. If one was a struct (i.e. a "value type"), then the enite thing would be copied.

于 2010-01-16T21:38:29.997 回答
2

You should have a look at passing by reference and passing by value. Your World object is a passed by reference, so you're passing a reference to a location in memory where the data this object contains resides.

Entity could now only access World object's public methods, properties.

于 2010-01-16T21:38:53.913 回答