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 是值类型,栈中就有两个值,彼此独立。

  • 相关阅读:
    异地主从双机热备份实战
    基于Crawler4j的WEB爬虫
    【转】TCP拥塞控制
    js定时器setTimeout和setInterval的使用
    制作 macOS Sierra U盘USB启动安装盘方法教程 (亲测)
    VMware 14 安装 macOS10.13 详细图文教程
    解决多线程下@Autowired无法注入
    MySQL 使用自增ID主键和UUID 作为主键的优劣比较详细过程(从百万到千万表记录测试)
    关于MYSQL
    关于Mybaits
  • 原文地址:https://www.cnblogs.com/happyframework/p/3575211.html
Copyright © 2011-2022 走看看