您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在C#中按引用或值传递对象

在C#中按引用或值传递对象

__根本不传递 对象认情况下,对参数进行求值,并按 将其 作为您所调用方法的参数的初始值传递。现在重要的一点是,该值是引用类型的引用- 一种访问对象(或null)的方法。从调用者可以看到对该对象的更改。但是,当您使用按值传递时,更改参数的值以引用另一个对象将 可见,这是 所有 类型的认值。

如果要使用按引用传递,则无论参数类型是值类型还是引用类型,都 必须 使用outref。在那种情况下,变量本身实际上是通过引用传递的,因此参数使用与参数相同的存储位置-并且调用者可以看到对参数本身的更改。

所以:

public void Foo(Image image)
{
    // This change won't be seen by the caller: it's changing the value
    // of the parameter.
    image = Image.FromStream(...);
}

public void Foo(ref Image image)
{
    // This change *will* be seen by the caller: it's changing the value
    // of the parameter, but we're using pass by reference
    image = Image.FromStream(...);
}

public void Foo(Image image)
{
    // This change *will* be seen by the caller: it's changing the data
    // within the object that the parameter value refers to.
    image.RotateFlip(...);
}

我有一篇文章将对此进行详细介绍。基本上,“通过引用”并不意味着您认为它意味着什么。

c# 2022/1/1 18:19:15 有420人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶