日期:2014-05-18  浏览次数:20867 次

引用类型和值类型的问题,难道string不是引用类型?看看这个错那了?
欲证明   C#   中引用类型,改变两个相等的引用类型,则另一个也随之改变。结果发现class   可以,但string不行。为什么?

Employee   ee1   =   new   Employee();
Employee   ee2   =   ee1;
现在,因为类在   C#   中为引用类型,所以   ee1   被视为对   Employee   的引用。在前面的两行中,第一行在内存中创建   Employee   的一个实例,并设置   ee1   以引用该实例。因此,将   ee2   设置为等于   ee1   时,它包含了对内存中的类的重复引用。如果现在更改   ee2   上的属性,则   ee1   上的属性将反映这些更改,因为两者都指向内存中的相同对象,如下所示:
原文:http://msdn2.microsoft.com/zh-cn/library/ms228360(vs.80).aspx

小实验如下:
Default2.aspx.cs代码
using   System;
using   System.Data;
using   System.Configuration;
using   System.Collections;
using   System.Web;
using   System.Web.Security;
using   System.Web.UI;
using   System.Web.UI.WebControls;
using   System.Web.UI.WebControls.WebParts;
using   System.Web.UI.HtmlControls;

public   partial   class   Default2   :   System.Web.UI.Page
{
        class   class1
        {
                public   int   vau   =   000;
        }
        protected   void   Page_Load(object   sender,   EventArgs   e)
        {
                string   str1   =   "str1   ";
                String   str2=str1;
                str2   =   "str1   xxx ";

                Label1.Text   =   str1;
                Label2.Text   =   str2;
 

                int   i   =   10;
                int   k   =   i;
                i   =   20;
                Label3.Text   =   i.ToString();
                Label4.Text   =   k.ToString();

                class1   a   =new   class1();
                class1   b   =   a;
                b.vau   =   123;
                Label5.Text   =   a.vau.ToString();
                Label6.Text   =   b.vau.ToString();

               
        }
}


Default2.aspx的代码
<%@   Page   Language= "C# "   AutoEventWireup= "true "   CodeFile= "Default2.aspx.cs "   Inherits= "Default2 "   %>

<!DOCTYPE   html   PUBLIC   "-//W3C//DTD   XHTML   1.0   Transitional//EN "   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<html   xmlns= "http://www.w3.org/1999/xhtml "   >