为什么System.Drawing中矩形,点,大小等可变的结构,而不是类? [英] Why are System.Drawing Rectangle, Point, Size etc mutable structs and not classes?

查看:105
本文介绍了为什么System.Drawing中矩形,点,大小等可变的结构,而不是类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还有一个原因是微软决定让这些结构?

Is there a reason Microsoft decided to make these structs?

这三种是可变的。我发现他们更容易对付,如果它们不是一成不变的,如果他们是引用类型。

All three are mutable. I would find them much easier to deal with if they were either immutable, or if they were reference types.

如果有原因,他们必须是结构,为什么他们可变的?

If there are reasons they must be structs, why are they mutable?

推荐答案

值语义
有这些值的两个相同的实例之间没有本质的区别。任何坐标, [2,3] 等于任何其它点具有相同的坐标,就像任何两个 INT s的类似的价值是相等的。 这是符合设计准则:

Why are they Structs

Value Semantics
There is no essential difference between two identical instances of these values. Any Point with coordinates, [2,3] is equal to any other point with the same coordinates, much like any two ints with similar value are equal. This is in conformance with the design guideline:

这在逻辑上重新presents一个值,类似于原始类型   (整数,双,等)。

It logically represents a single value, similar to primitive types (integer, double, and so on).

性能

值类型便宜分配和释放。

Value types are cheaper to allocate and deallocate.

有经常要求创建这些值的许多实例。结构成本更低创建,并且如果它们的本地值,它们将在堆栈上被创建,从GC减轻pressure

There is often requirement to create many instances of these values. Structs cost less to create, and if they are local values, they will be created on the stack, relieving pressure from the GC.

尺寸
让我们考虑这些数值的大小:
:8个字节
尺寸:8个字节
矩形:16字节

Size
Let's consider the size of these values:
Point : 8 bytes
Size: 8 bytes
Rectangle: 16 bytes

有关尺寸,它们的大小是一样的引用类实例将在一个64位 系统中。

For Point and Size, their size is the same as a reference to a class instance would be in a 64-bit system.

行情:选择类和结构之间

这些结构是完全可变的。这样做是(上日准则)为了性能,因为它避免了需要用于修改操作创建新的值。

These structs are fully mutable. This is done (against the guidelines) for the sake of performance, as it avoids the need to create new values for modification operations.

关于注释中的OP的code例如:

Regarding the OP's code example in the comments:

Point[] points = new Point[] { new Point(0,0), new Point(1,1), new Point(2,2) };

foreach (Point p in points)
{
    p.X += 1; 
}

的foreach 失败的唯一原因,是因为 P 盒装,以便对象来提供迭代,你无法修改拆箱转换,结果,你只会更改到的复制的价值。

The only reason this foreach fails, is because p is boxed to object in order to provide iteration, and you Cannot modify the result of an unboxing conversion, as you would only be making changes to the copy of the value.

这工作得很好:

for (int i = 0; i < points.Length; i++)
{
    points[i].X += 1;
}

这篇关于为什么System.Drawing中矩形,点,大小等可变的结构,而不是类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆