C#引用传递
来源:互联网 发布:linux $$ 编辑:程序博客网 时间:2024/05/18 18:42
学过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>
- C# 按引用传递
- C#引用传递
- C#引用传递
- C#引用传递
- C#引用传递
- c#引用传递和值传递
- C#中的引用传递、值传递。
- C#中的引用传递、值传递
- C#中的引用传递和值传递
- C#中的引用传递、值传递
- C#值传递与引用传递
- C#中的引用传递、值传递。
- C#中的引用传递和值传递
- C#中的引用传递、值传递。
- C#中的引用传递、值传递
- C#中值传递和引用传递
- C# 值传递和引用传递
- C#中的引用传递、值传递。
- REST风格
- No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
- Hive学习二
- POJ 3264 Balanced Lineup RMQ
- [从头学数学] 第184节 周游列国拜诸侯(中)
- C#引用传递
- HDU 5666 快速就乘
- 用pipe唤醒异步select的经典场景
- __NSCFNumber isEqualToString:的问题.--[__NSCFNumber isEqualToString:]: unrecognized selector sent to in
- vs下,GBK格式的.h .cpp 编译时,自动转换为UTF-8
- Java学习-11天
- 剑指offer面试题 顺时针打印矩阵
- 一个用PHP写的网站,当两个人同时用一个账号登录时,后一个会将前一个账号挤下线。
- leetcode 9 给一个int类型的数字,判断是否是回文数