public class MyClass{public string Name { get; set; }}
public void Foo(){MyClass myObject = new MyClass();myObject.Name = "Dog";Bar(myObject);Console.WriteLine(myObject.Name); // Writes "Dog".}
public void Bar(MyClass someObject){MyClass myTempObject = new MyClass();myTempObject.Name = "Cat";someObject = myTempObject;}
(inside method) reference2.Add("SomeString");(outside method) reference1[0] == "SomeString" //this is true
如果您将引用2清空或将其指向新数据,它不会影响引用1,也不会影响引用1指向的数据。
(inside method) reference2 = new List<string>();(outside method) reference1 != null; reference1[0] == "SomeString" //this is true
The references are now pointing like this:reference2 => new List<string>()reference1 => someobject
string a = "Hello";
string b = "goodbye";
b = a; //attempt to make b point to a, won't work.
a = "testing";
Console.WriteLine(b); //this will produce "hello", NOT "testing"!!!!
using System;
namespace CalculatorApplication{class NumberManipulator{public void getValue(out int x ){int temp = 5;x = temp;}
static void Main(string[] args){NumberManipulator n = new NumberManipulator();/* local variable definition */int a = 100;
Console.WriteLine("Before method call, value of a : {0}", a);
/* calling a function to get the value */n.getValue(out a);
Console.WriteLine("After method call, value of a : {0}", a);Console.ReadLine();
}}}
using System;namespace CalculatorApplication{class NumberManipulator{public void swap(ref int x, ref int y){int temp;
temp = x; /* save the value of x */x = y; /* put y into x */y = temp; /* put temp into y */}
static void Main(string[] args){NumberManipulator n = new NumberManipulator();/* local variable definition */int a = 100;int b = 200;
Console.WriteLine("Before swap, value of a : {0}", a);Console.WriteLine("Before swap, value of b : {0}", b);
/* calling a function to swap the values */n.swap(ref a, ref b);
Console.WriteLine("After swap, value of a : {0}", a);Console.WriteLine("After swap, value of b : {0}", b);
Console.ReadLine();
}}}
double nbr = 6; // if not initialized we get errordouble dd = doit.square(ref nbr);
double Half_nbr ; // fine as passed by out, but inside the calling method you initialize itdoit.math_routines(nbr, out Half_nbr);
ref是一个关键字,用于通过引用传递任何值(参考编程中的按值调用和按引用调用以获取更多知识)。简而言之,你声明并初始化一个值,例如让我们说int age = 5;,这样这个年龄通过保存4个字节的位置保存在内存中。现在,如果你使用ref将这个年龄变量传递给另一个方法(这意味着通过引用而不是通过值传递它们),那么编译器将只传递该变量的引用,或者明确地说,传递存储变量的地方的内存地址,被调用的方法接收这个地址并直接访问该地址中的数据。因此,显然对该数据的任何更改也会发生在调用方法中存在的变量上。