zoukankan      html  css  js  c++  java
  • 值类型与引用类型

    ---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

      在C#中,类型主要分为两种,一种是值类型,一种是引用类型。

      所有的值类型都隐式的继承自System.ValueType类型,所有的引用类型都隐式的继承System.Object。

      值类型与引用类型主要区别在于, 值类型是在栈中分配存储空间的,引用类型是在堆中分配存储空间的,但引用类型的引用时存在栈中的。

      C#中的值类型

    • 数值类型:sbyte, short, int, long, byte, ushort, uint, ulong, char, float, double, decimal
    • 布尔类型:bool
    • 结构体:struct
    • 枚举类型:enum

      C#中的引用类型

    • 数组:派生字System.Array
    • 类:class
    • 接口:interface
    • 委托:delegate
    • Object类型
    • 字符串:string
    int x = 5;
    

    对于上面的赋值,因为int是值类型,所以它是存储在栈上的

      

    string s = "hello";
    

    对于上面的赋值,因为string是引用类型,所以它的数据实际上是存在堆上的,而引用时存在栈中的,变量s保存的就是这个引用,而不是"hello"这个字符串。在C语言中,就是"hello"存在堆中,而栈中存放的是"hello"在堆中的指针。

    class Program_1
    {
        static void Main(string[] args)
        {
            int x = 5;
            string s = "hello";
            Info info;
            info.name = "me";
            info.age = 20;
            info.adress = new Adress("China", "Wuhan", "secret");
        }
    }
    struct Info
    {
        public string name;
        public int age;
        public Adress adress;
    }
    class Adress
    {
        public Adress(string state, string city, string street)
        {
            this.State = state;
            this.City = city;
            this.Street = street;
        }
        public string State { get; set; }
        public string City { get; set; }
        public string Street { get; set; }
    }
    

    上面的代码是一个值类型和引用类型嵌套的例子:

  • 相关阅读:
    网络流之对偶图转最短路
    BZOJ5418 NOI2018屠龙勇士EXCRT
    BZOJ1951 [Sdoi2010]古代猪文 NOIP数论大杂烩
    中国剩余定理及EX及单层EXLucas定理讲解
    网络流24题之负载平衡问题
    输入一个url到浏览器页面展示都经历了哪些过程
    前端部署dist包到服务器
    img标签显示 base64格式的 图片
    字符串用react 用sha256加密
    前端下载证书文件cer用后端返回的加密数据
  • 原文地址:https://www.cnblogs.com/hourglasser/p/3405020.html
Copyright © 2011-2022 走看看