c# 将类类型成员作为参数传递作为按值调用

标签 c# call-by-value

据我所知,类类型参数总是作为引用传递。 但是每当我传递一个作为类成员的类类型变量作为参数时。它总是像 按值调用。

public class MapGenerator : MonoBehaviour
{
   [SerializeField]
    private List<MapEntity> stageTerrains = new List<MapEntity>();
    private MapEntity stageTerrain = new MapEntity();

    private void Start()
    {
        RandomChoice(stageTerrains);
    }


    public void RandomChoice(MapEntity mapEntity)
    { 
        mapEntity = stageTerrains[Random.Range(0,selectedList.Count)];
        Print(mapEntity);  //it always works well 
        Print(stageTerrain);  // always print null
    }
}

所以我在参数中添加了一个 ref 关键字,它就像按引用调用一样工作

public class MapGenerator : MonoBehaviour
{
   [SerializeField]
    private List<MapEntity> stageTerrains = new List<MapEntity>();
    private MapEntity stageTerrain = new MapEntity();

    private void Start()
    {
        RandomChoice(ref stageTerrains);
    }


    public void RandomChoice(ref MapEntity mapEntity)
    { 
        mapEntity = stageTerrains[Random.Range(0,selectedList.Count)];
        Print(mapEntity);  //it always works well 
        Print(stageTerrain);  // print well too 
    }
}

我想知道为什么将类类型成员作为参数传递就像按值调用一样工作

最佳答案

From the ref documentation

When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable.

因此,我将尝试尽可能简单地解释使形式参数成为别名

没有引用

private MapEntity stageTerrain = new MapEntity(); 中的 stageTerrain 想象成一个包含地址的盒子。

public void RandomChoice(MapEntity mapEntity) 中的 mapEntity 想象成另一个 NEW 框。

  • 如果在分配新对象之前更改 mapEntity 的属性,它也会更改调用变量的值。

当您调用 RandomChoice 时,mapEntity 是一个新框,其内存地址与 stageTerrain 框相同。

现在 mapEntity = stageTerrains[Random.Range(0,selectedList.Count)]; 只会将所选值分配给 New 框。

引用

public void RandomChoice(ref MapEntity mapEntity) 中的 mapEntity 想象成一个已经存在的框的别名,该框将使用不同的名称保存内存引用。 (因此别名声明)

当您调用 RandomChoice 时,mapEntity stageTerrain 框。

关于c# 将类类型成员作为参数传递作为按值调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65994468/

相关文章:

c# - ASP .NET C# - 将圆形 SqlDataSource 放入方形 DataTable 孔中?

c# - "\n"和 Environment.NewLine 的区别

c# - 设置窗体的 MdiParent 属性会中断/阻止触发其 Shown 事件

c++ - 我可以按值(复制)从一个 std::vector 插入一个对象到另一个吗?

compiler-construction - 在按名称调用和按值调用下会打印什么?

c# - 从 WebApi 返回图像

c# - 如果我在 c# 中注册一个事件,而它正在调度,我是否保证在该调度期间不会再次被调用?

c++ - 为什么在此代码中当 "swap"函数写在 int main() 之后而不是之前时会发生交换?

c - 传递地址,但它的工作方式类似于 C 中的按值调用?

java - 重访按值调用与按引用调用