由于“1.ToString()”的结果是String类型,属于引用类型,因此不牵扯装箱和拆箱操作。
其次,牵扯到装箱和拆箱操作比较多的就是在集合中,例如:ArrayList或者HashTable之类。
把值类型数据放到集合中,可能会出现潜在错误。例如: public struct Person { private string _Name; public string Name { get{ return _Name; } set{ _Name = value; } } public Person( string PersonName ) { _Name = PersonName; } public override string ToString() { return _Name; } } // Using the person in a collection ArrayList arrPersons = new ArrayList(); Person p = new Person( "OldName" ); arrPersons.Add( p ); // Try to change the name p = ( Person ) arrPersons[0] ; p.Name = "NewName"; Debug.WriteLine( ( (Person ) arrPersons[0] ).Name );//It's "OldName"
这个问题其实在前面的文章中已经讲过了。有人可能会说,是否可以按照如下的方式去修改呢。 ( (Person ) arrPersons[0] ).Name = "NewName";//Can't be compiled
很不幸,如上操作不能通过编译。为什么呢,对于“( (Person ) arrPersons[0] )”来说,是系统用一个临时变量来接收拆箱后的值类型数据,那么由于值类型是分配在栈上,那么操作是对实体操作,可是系统不允许对一个临时值类型数据进行修改操作。
// Using the person in a collection ArrayList arrPersons = new ArrayList(); Person p = new Person( "OldName" ); arrPersons.Add( p ); // Try to change the name p = ( Person ) arrPersons[0] ; p.Name = "NewName"; arrPersons.RemoveAt( 0 );//Remove old data first arrPersons.Insert( 0, p );//Add new data Debug.WriteLine( ( (Person ) arrPersons[0] ).Name );//It's "NewName"
(编辑:aniston)
|