8.8 Structs

博客介绍了C#中struct和class的异同。struct是值类型,不支持继承,值存储在栈或内联。合理使用struct可提升性能,如用struct实现Point可减少运行时内存分配,但使用不当也会使应用变慢或占用更多内存,因按值传递会创建副本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值