传递对象通过引用或值在C# [英] Passing Objects By Reference or Value in C#

查看:149
本文介绍了传递对象通过引用或值在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我一直认为非原始变量引用传递,原始值按值传递的。

In C#, I have always thought that non-primitive variables were passed by reference and primitive values passed by value.

所以传递给方法的任何非原始对象时,任何事情到对象中的方法会降低对象被传递。 (C#101的东西)

So when passing to a method any non-primitive object, anything done to the object in the method would effect the object being passed. (C# 101 stuff)

不过,我注意到,当我通过一个为System.Drawing.Image对象,这似乎并没有这样的情况?如果我通过一个为System.Drawing.Image对象的另一种方法,并加载图像到该对象,然后让该方法走出去的范围,并返回给调用的方法,即图像不加载原来的对象?

However, I have noticed that when I pass a System.Drawing.Image object, that this does not seem to be the case? If I pass a system.drawing.image object to another method, and load an image onto that object, then let that method go out of scope and go back to the calling method, that image is not loaded on the original object?

这是为什么?

推荐答案

对象的一点都过去了。默认情况下,参数计算和它的的传递,按值,因为我们正在调用方法的参数的初始值。现在,重要的一点是,该值是引用类型的引用 - 让一个对象(或空)的方法。改变该对象会从呼叫者可见。但是,更改参数的值来引用不同的对象的的,当你使用按值传递,这是默认的是可见的所有的类型。

Objects aren't passed at all. By default, the argument is evaluated and its value is passed, by value, as the initial value of the parameter of the method you're calling. Now the important point is that the value is a reference for reference types - a way of getting to an object (or null). Changes to that object will be visible from the caller. However, changing the value of the parameter to refer to a different object will not be visible when you're using pass by value, which is the default for all types.

如果你想使用传递通过引用,你的必须的使用退出 REF ,参数类型是值类型或引用类型。在这种情况下,有效地变量本身通过引用传递,所以该参数使用相同的存储位置作为参数 - 和参数本身的变化是由主叫方看到

If you want to use pass-by-reference, you must use out or ref, whether the parameter type is a value type or a reference type. In that case, effectively the variable itself is passed by reference, so the parameter uses the same storage location as the argument - and changes to the parameter itself are seen by the caller.

所以:

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(...);
}

我有一个文章,其中进入了很多更详细的这。基本上,通过引用传递并不意味着你认为它的意思。

I have an article which goes into a lot more detail in this. Basically, "pass by reference" doesn't mean what you think it means.

这篇关于传递对象通过引用或值在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆