有关C# struct的一个误区

参考:http://blog.csdn.net/onlyou930/article/details/5568319

下面写一个新的例子:

 using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication1
{
public struct Rectangle
{
private int height;
public int Height
{
get { return height; }
set { height = value; }
} private int width;
public int Width
{
get { return width; }
set { width = value; }
} public Rectangle(int a,int b)
{
height = a;
width = b;
}
} class Program
{
static void Main(string[] args)
{
List<Rectangle> rectangle = new List<Rectangle>() { new Rectangle() };
rectangle[].Height = ;
rectangle[].Width = ;
} }
}

代码写完之后,有代码有错误:
有关C# struct的一个误区

编译生成后“错误列表”中显示:

有关C# struct的一个误区

出现这个问题的原因分析:

在以上代码中,rectangle是引用类型,rectangle的对象在堆上,虽然rectangle[0]是值类型,但它是rectangle的组成部分,仍然在堆上,而值类型默认是按值传递,所以将rectangle[0]的值做临时的拷贝到栈上,我们暂且称之为temp_rectangle[0],

temp_rectangle[0].Height=20;

temp_rectangle[0]的值是变了,但是rectangle[0]的值并不会改变,所以上面错误代码中的赋值操作是没有意义的,故编译器直接不让编译通过。

在实际中,我们通常似乎需要完成类似的功能,那怎么办呢?有两种解决途径,1)将struct改成class,class是引用类型,就不存在值传递的问题了;2)做一个对象替换,具体代码如下:

  class Program
{
static void Main(string[] args)
{
//List<Rectangle> rectangle = new List<Rectangle>() { new Rectangle() };
var rectangle = new Rectangle();
rectangle.Height = ;
rectangle.Width = ;
List<Rectangle> listRectangle = new List<Rectangle>() { rectangle};
}
}

Height和Width的值如下:
有关C# struct的一个误区

解决方案2用新的对象替代了原来的对象。

总结完毕。

上一篇:ACM题目————二叉树最大宽度和高度


下一篇:An incompatible version [1.1.29] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]