zoukankan      html  css  js  c++  java
  • .NET:默认是按值传递的

    小测试

    代码

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 using System.Linq.Expressions;
     7 using System.Threading;
     8 
     9 namespace CSharpStudy
    10 {
    11     class Program
    12     {
    13         static void Main(string[] args)
    14         {
    15             {
    16                 var t1 = new TestClass();
    17                 var t2 = TestMethod1(t1);
    18 
    19                 Console.WriteLine(t1.Value);
    20                 Console.WriteLine(t2);
    21             }
    22             {
    23                 var t1 = new TestClass();
    24                 var t2 = TestMethod2(ref t1);
    25 
    26                 Console.WriteLine(t1);
    27                 Console.WriteLine(t2);
    28             }
    29         }
    30 
    31         private static TestClass TestMethod1(TestClass test)
    32         {
    33             test.Value = 10;
    34             test = null;
    35             return test;
    36         }
    37 
    38         private static TestClass TestMethod2(ref TestClass test)
    39         {
    40             test.Value = 10;
    41             test = null;
    42             return test;
    43         }
    44     }
    45 
    46     internal class TestClass
    47     {
    48         public int Value { get; set; }
    49     }
    50 }

    输出

    如果输出结果你不意外,也能理解到底发生了什么,那么就不用看这篇文章了。

    默认是按值传递的

    var a = new TestClass(); 中 a 叫“reference”,等号右侧叫“instance”,作为局部变量的 reference 分配在栈中,作为成员的 reference 内联存储在堆中,instance 始终分配在堆中,reference 指向了 instance,可以理解为存储了 instance 的地址。

    var a = new TestStruct(); 中 a 叫“value”,右侧返回的值就分配在 a 中,作为局部变量的 value 分配在栈中,作为成员的 value 内联存储在堆中。

    .NET 默认是按值进行传递的(参数传递、变量之间的赋值),var a = b; 中如果 b 是引用类型,栈中就有两个引用,一个对象,两个引用共同指向同一个对象。如果 b 是值类型,栈中就有两个值,彼此独立。

  • 相关阅读:
    使用注解@Slf4j简化Logger的初始化
    Windows系统CPU和内存状态实时查询(Java)
    Windows下压缩包安装Mysql
    ubuntu安装IntelliJ Idea及图标创建
    【CSS】使用边框和背景
    【CSS】使用CSS选择器(第二部分)
    【CSS】使用CSS选择器
    【CSS】理解CSS
    【HTML5】使用多媒体
    【HTML5】嵌入另一张HTML文档、通过插件嵌入内容、嵌入数字表现形式
  • 原文地址:https://www.cnblogs.com/happyframework/p/3575211.html
Copyright © 2011-2022 走看看