使用更多的结构?(use MORE structs?)

2019-09-02 11:39发布

There have been several questions over the past few days about the proper use of null; here are three (one is mine):

  • Best Practice: Should functions return null or an empty object?
  • null objects vs. empty objects
  • how do i explain that if (xyz == null) checks are not “protective”.

While reading and thinking about this issue, the thought occured to me: why not use struct instead of class? (I then read some of the many questions about just that.)

One big benefit of a struct (in this context) is that it can't be null, so there is never a need to check against null. And as an added bonus, if you really want a null struct you can do that too with some extra syntax (T?) and the Nullable<> type. (Too bad reference types didn't work like this too!)

But structs are passed by value which kills performance. Well, first, code should be "right" (whatever that might mean) and then fast. However, there are several ways to avoid that overhead where it really matters: ref parameters, nullable parameters, place the struct in some other class, say List<>.

True, with structs, you can't create a class hierarchy, but "inheritence is overused". And you can implement interfaces.

Using more struct-based objects could make writing multi-threaded code easier.

Are there any more infrequently cited advantages to structs? Do any of these considerations even come close to putting a dent in class's massive "head start"?

Answer 1:

一的一大限制(IMO) struct是,它应该是一成不变的。

我已经多次定义和使用用户定义的结构,为你的建议的原因(即因为结构不能为空。); 但当时我经常(直到我学会了从来没有让他们什么,但不变)通过修改结构实例的副本(有时未命名的临时副本),而不是通过修改实例本身烧毁。



Answer 2:

我想你应该只是坚持到空对象 ,具有创造性这样只会让你陷入困境,而且可能使代码少维护。



Answer 3:

如果开始在弱类型场景使用结构(如分配到一个对象类型) Object o = structValue;Object o = new mystruct();Object o = default(mystruct); 等的值被盒装到堆上,并且它们也装箱一起使用时。 这是一个潜在的缺点,因为它会影响性能。 看到来自微软的信息装箱和拆箱 。



文章来源: use MORE structs?