C#系列 ----- 3 值引用和对象引用

值类型和引用类型(Value Types Versus Reference Types)

上一篇对于type的定义其实不准确,在此给出更准确的定义。

所有的C#类型包括:

  • Value types
  • Reference types
  • Generic type parameters
  • Pointer types

先看一下值类型和引用类型,其余的之后再看

  • 值类型: 内建的 all numeric types, the char type, and the bool type和自定义的structenum类型
  • 引用类型:class, array, delegate, and interface types 和内建的string type

两者的基本不同是在内存中的处理方式不同

  1. Value types
    值类型的变量或常量仅仅是一个值,比如内建整型int的变量仅仅是一个32位的数据

    public struct Point { public int X, Y; }
    

    在这里插入图片描述

    对于值类型而言,实例赋值直接深拷贝一份,即创建另一份内存

   static void Main()
{
Point p1 = new Point();
p1.X = 7;
Point p2 = p1; // Assignment causes copy
Console.WriteLine (p1.X); // 7
Console.WriteLine (p2.X); // 7
p1.X = 9; // Change p1.X
Console.WriteLine (p1.X); // 9
Console.WriteLine (p2.X); // 7
}

在这里插入图片描述

  1. 引用类型
    引用类型包含两部分: 对象和对象的引用。而引用类型的实例对象是包含值得对象的引用。简单的就是一个指向内存的指针,指向的内存中包含值。和C++的指针一样
    在这里插入图片描述

在这里插入图片描述


Null: 引用可以赋值为null, 表示没有指向任何对象

class Point {...}
...
Point p = null;
Console.WriteLine (p == null); // True
// The following line generates a runtime error
// (a NullReferenceException is thrown):
Console.WriteLine (p.X);

而值不可以赋值为null

struct Point {...}
...
Point p = null; // Compile-time error
int x = null; // Compile-time error

内存占用(Storage overhead)

  • 值类型实例精确地占用了存储字段所需的内存
    下面的Point占用8个字节
struct Point
{
int x; // 4 bytes
int y; // 4 bytes
}

而引用类型需要为对象和引用(指针)分配内存,需要的内存更大


  • 位操作符:
    在这里插入图片描述

  • 条件操作符

    || && != ==

    res = q ?a : b => if q{ res= a} else{res=b}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值