使用更多的结构?结构、更多

2023-09-05 02:37:05 作者:浓情岁末

已经有几个问题,在过去几天里对正确使用的空的;这里有三个(一个是我的):

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

Best做法:?如果函数返回null或一个空对象 空物体与空对象 how做我解释说,如果(XYZ == NULL)检查是不是保护。 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.)

一个大的利益而结构(在这方面)是的不能为null 的,所以从来没有必要核对。而作为一个额外的好处,如果你真的想要一个空结构,你可以做到这一点与一些额外的语法( T?)和可空<> 键入。 (太糟糕了,引用类型不喜欢这个工作呢!)

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!)

结构 S被值杀死性能通过。嗯,首先,code应该是正确的(任何的是的可能意味着),然后快速。但是,有几种方法,以避免开销,它真的很重要: REF 参数,可为空参数,将结构在其它的类,比如名单,其中;&GT;

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<>.

真,与结构 S,你不能创建一个类层次结构,但传承是过度使用。而且你可以实现接口。

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

使用更多的结构为基础的对象可以使编写多线程code更容易。

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

是否有其他不经常引用的优势,以结构 S'做这些方面的考虑,甚至接近放一个凹痕的声势浩大的先声夺人?

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"?

推荐答案

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

The big limitation (IMO) of a struct is that it ought to be immutable.

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

I have several times defined and used a user-defined struct, for the reason you suggested (ie. because a struct can't be null); but I was then often (until I learned to never make them anything but immutable) burned by modifying a copy (sometimes an unnamed temporary copy) of a struct instance, instead of modifying the instance itself.

 
精彩推荐
图片推荐