对象根本没有被传递。默认情况下,参数会被求值,它的价值会作为你调用的方法的参数的初始值被传递。现在重要的一点是,该值是引用类型的引用——一种获取对象(或null)的方式。对该对象的更改将从调用者可见。然而,当你使用pass by value(这是所有类型的默认值)时,改变形参的值以引用不同的对象将会显示不。
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(...);
}
YourMethod(System.Drawing.Image image)
{
//now this image is a new reference
//if you load a new image
image = new Image()..
//you are not changing the original reference you are just changing the copy of original reference
}
In Pass By Reference你只在函数参数中添加“ref”和一个
你应该声明函数为“static”,因为main是static(#public void main(String[] args))!< / p >
namespace preparation
{
public class Program
{
public static void swap(ref int lhs,ref int rhs)
{
int temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args)
{
int a = 10;
int b = 80;
Console.WriteLine("a is before sort " + a);
Console.WriteLine("b is before sort " + b);
swap(ref a, ref b);
Console.WriteLine("");
Console.WriteLine("a is after sort " + a);
Console.WriteLine("b is after sort " + b);
}
}
}
Employee e = new Employee();
e.Name = "Mayur";
//Passes the reference as value. Parameters passed by value(default).
e.ReferenceParameter(e);
Console.WriteLine(e.Name); // It will print "Shiv"
class Employee {
public string Name { get; set; }
public void ReferenceParameter(Employee emp) {
//Original reference value updated.
emp.Name = "Shiv";
// New reference created so emp object at calling method will not be updated for below changes.
emp = new Employee();
emp.Name = "Max";
}
}