值类型与引用类型

---------------------- 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; }
}

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

原文地址:https://www.cnblogs.com/hourglasser/p/3405020.html