博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

简单讲讲值类型里包含引用类型

Posted on 2010-11-06 15:10  Mr.X  阅读(532)  评论(2编辑  收藏  举报

最近看书看到值类型包含引用类型的时候看到了一个有趣的问题  闲话少说直接进入正题

 

string a="one";
string b = a;
b
="two";
console.write(a);

这段代码 大家因该都知道 最后输出的结构是 one 虽然 string 是引用类型,但实际在执行 b=a这个操作的时候 在CIL里面 其实是产生了一个 a="one"的副本 然后将副本传给了b 而A的原始值会一直到下次GC的时候被处理掉。 这就是string这个引用类型 显示出值类型特征的原因。 那让我们来看看下面这段代码:

class ShapeInfo
{
public string infoString;
public ShapeInfo(string info)
{
infoString
= info;
}
}

struct Rectangle
{
public ShapeInfo rectInfo;
public int rectTop, rectLeft, rectBottom, rectRight;
public Rectangle(string info, int top, int left, int bottom, int right)
{
rectInfo
= new ShapeInfo(info);
rectTop
= top;
rectRight
= right;
rectLeft
= left;
rectBottom
= bottom;
}

public void DisPlay()
{
Console.WriteLine(
"string={0},top={1},left={2},bottom={3},right={4}", rectInfo.infoString, rectTop, rectLeft, rectBottom, rectRight);
}
}

 

这里我们创建了一个类 在类里面有一个字符串类型的字段 还有一个方法 ,然后我们创建了一个结构 结构大家应该都知道是值类型的 然后在结构里面实例化 shapeInfo类 然后给它传值。 接下来我们再 来看看 调用

 

static void Main(string[] args)
{
Rectangle r1
= new Rectangle("First Rect", 10, 10, 50, 50);
Rectangle r2
= r1;
r2.rectInfo.infoString
= "This is new info";
r2.rectBottom
= 4444;
r1.DisPlay();
}

 

看了这段代码 你也许会说 最后的输出结果肯定是 First 因为前面说过了 是在CIL里面创建了一个字符串的副本 哈哈 那就错了 最后输出的结果 会是 this is new info 这时你也许在说 为什么会是这样。 其实在r2=r1 的时候 引用类型 传给R1 的是一个 内存地址的引用 这种复制 称为 浅复制  当然想进行深复制也可以 需要实现一个结构 以后再和大家讨论 呵呵 我也是新手如有不对之处欢迎大家指正。 最后 对你们在百忙之中看我的文章 表示感谢 呵呵