学过C#的人都知道,通过值或通过引用,值类型和引用类型都可以作为方法参数传递。在C#中,不管是值类型或者是引用类型,所有方法参数在默认情况下是通过值传递的。
1)通过值传递值类型
- using System;
- class MyExecutableClass
- {
- static void Main(string[] args)
- {
- int value=50;
- DoSometing(value);
- Console.WriteLine(value);
- }
- static void DoSomething(int parameter)
- {
- parameter=100;
- }
- }
- using System;
- class MyExecutableClass
- {
- static void Main(string[] args)
- {
- int value=50;
- DoSomething(ref value);
- Console.WriteLine(value);
- }
- static void DoSomething(ref int parameter)
- {
- parameter=100;
- }
- }
3)通过值传递引用类型
内存中对象实际位置的引用。因此,如果通过值传递引用类型,就意味着传递的是对象的引用(它的堆栈)
.使用该引用作的改变最终会改变堆中的同一对象。
我们将Person用作引用类型。
- using System;
- class MyExecutableClass
- {
- static void Main(string[] args)
- {
- Person person=new Person(50);
- DoSomething(person);
- Console.WriteLine(person.Age);
- }
- static void DoSomething(Person somePerson)
- {
- somePerson.Age=100;
- }
- }
- class Person
- {
- public int Age;
- public Person(int Age);
- {
- this.Age=Age;
- }
- }
如果对DoSometing方法作如下修改;
- static void DoSomething(Person somePerson)
- {
- somePeron=new Person(100);
- }
调用DoSomething()方法时,我们创建了一个引用副本,它仍然指向同一对象,因此,对对象的改变会影响主程序。而对引用的改变则不会,在方法结束时,消失的只是引用的副本。
2。但接下来是创建一个新对象,改变引用来指向它---对引用的改变将会丢失。
- <pre name="code" class="csharp"></pre><pre name="code" class="csharp">using System;
- class MyExecutableClass
- {
- static void Main(string[] args)
- {
- Person person=new Person(50);
- DoSometing(ref person);
- Console.WriteLine(person.Age);
- }
- static void DoSometing(ref Person somePerson)
- {
- somePerson=new Person(100);
- }</pre><pre name="code" class="csharp">} </pre>
- <pre></pre>