编程语言
首页 > 编程语言> > 另一个“为什么结构不可变?” C#

另一个“为什么结构不可变?” C#

作者:互联网

我读了
When should I use a struct instead of a class?
引用了MSDN的指导,其中指出:

Do not define a structure unless the
type has all of the following
characteristics:

  • It logically represents a single value, similar to primitive types
    (integer, double, and so on).
  • It has an instance size smaller than 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.

并且Why are mutable structs “evil”?有答案:

Structs are value types which means they are copied when they are passed around.

我正在努力理解为什么我不只是意识到结构需要通过引用进行传递,否则对通过函数传递的版本进行的更改不会影响原始结构.是的,过去我有过很多错误,但是现在我已经足够经验了,我很小心不要发生这种情况.

我专门使用C#制作游戏,并且游戏中的内容变量需要大量更改.

假设我有一个玩家角色,在游戏中以“玩家”类表示.如果播放器具有变量X和Y来说明其位置,则它们将发生很大变化.我不想每次移动都创建一个新Player只是为了保持不变性?所以我的课应该是可变的.好.

但是,如果我想存储有关实体的数据该怎么办.如果我将其位置存储在屏幕上的Rectangle(x,y,w,h)中,是否应该将Rectangle设为CLASS,因为它将变得易变?它只是4个变量的逻辑集合,因此对我来说,结构作为容器似乎是明智的.

我也将“颜色”作为结构(r,g,b,a),但我认为它是可变的,因为我可能想改变游戏中事物的alpha值以使其淡入/淡出,或为红色着色受伤时可以使用1秒钟,而无需每次渲染调用都调用“ new Colour”的开销.

我看到另一个帖子说如果满足以下条件,则应使用结构:

  • Is the main responsibility of the type data storage?
  • Is its public interface defined entirely by properties that access or modify its data members?
  • Are you sure your type will never have subclasses?
  • Are you sure your type will never be treated polymorphically?

对于我使用的结构,答案是“是”,但大多数结构都是可变的.

我对这里所有矛盾的建议感到困惑.可变结构可以用于某些类型的使用,还是我在设计代码时都错了?

解决方法:

这不仅仅是偶然丢失信息的机会:

list.ForEach(item => item.X = 10);
// this code does nothing useful if item is a mutable struct

也是the weird interaction between mutating methods and readonly

readonly MutableStruct m_field;
...
m_field.MutatingMethod(); // mutates a temporary copy rather than the field

但是,如果您通过分析确定:

>您无法负担参考类型,因为,例如,GC压力,或者您
想要将所有对象放置在数组中以获得更好的局部性
>修改时,您无法复制整个结构
>您无法合理地更改设计以解决这些问题(使结构更小,具有引用类型的对象池等).
>你知道你在做什么

然后,可变结构可能就是您所需要的.这就是为什么他们毕竟使用该语言.

说到游戏代码,SharpDX充满了可变的结构(example)和通过引用传递的方法.

标签:struct,immutability,game-engine,c
来源: https://codeday.me/bug/20191118/2030567.html