__根本不传递 对象 。默认情况下,对参数进行求值,并按 值 将其 值 作为您所调用方法的参数的初始值传递。现在重要的一点是,该值是引用类型的引用- 一种访问对象(或null)的方法。从调用者可以看到对该对象的更改。但是,当您使用按值传递时,更改参数的值以引用另一个对象将 不 可见,这是 所有 类型的默认值。
如果要使用按引用传递,则无论参数类型是值类型还是引用类型,都 必须 使用out
或ref
。在那种情况下,变量本身实际上是通过引用传递的,因此参数使用与参数相同的存储位置-并且调用者可以看到对参数本身的更改。
所以:
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(...);
}
我有一篇文章将对此进行详细介绍。基本上,“通过引用”并不意味着您认为它意味着什么。