8.8 Structs

王朝other·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

8.8 Structs

The list of similarities between classes and structs is long.structs can

implement interfaces, and can have

the same kinds of members as classes. Structs differ from classes in

several important ways, however:

C# LANGUAGE SPECIFICATION

42

structs are value types rather than reference types, and inheritance is not

supported for structs. Struct values

are stored .on the stack. or .in-line.. Careful programmers can sometimes

enhance performance through

judicious use of structs.

For example, the use of a struct rather than a class for a Point can make a

large difference in the number of

memory allocations performed at run time. The program below creates and

initializes an array of 100 points.

With Point implemented as a class, 101 separate objects are

instantiated.one for the array and one each

for the 100 elements.

class Point

{

public int x, y;

public Point(int x, int y) {

this.x = x;

this.y = y;

}

}

class Test

{

static void Main() {

Point[] points = new Point[100];

for (int i = 0; i < 100; i++)

points[i] = new Point(i, i*i);

}

}

If Point is instead implemented as a struct, as in

struct Point

{

public int x, y;

public Point(int x, int y) {

this.x = x;

this.y = y;

}

}

only one object is instantiated.the one for the array. The Point instances

are allocated in-line within the

array. This optimization can be misused. Using structs instead of classes

can also make an application run

slower or take up more memory, as passing a struct instance by value causes

a copy of that struct to be

created.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航