不可变类VS永恒结构 [英] Immutable class vs Immutable struct

查看:96
本文介绍了不可变类VS永恒结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有开始生活是可变的一类,但我既然做它一成不变的。我应该改变它是一个结构?进入选择了另一种什么样的考虑?我的具体情况是最多的4 INT 键入类(它代表了一个自定义坐标系的坐标) C>字段,加上一些属性来访问不同的方式相同的数据。我注意到,字符串是一类,并且是不变的,所以必须有一些用例这一点。

I have a class that started life being mutable, but I've since made it immutable. Should I change it to be a struct? What sort of considerations go into choosing one over the other? My particular case is a Point type class (it represents a coordinate in a custom coordinate system) that is made up of 4 int fields, plus a few properties to access the same data in different ways. I note that String is a class and is immutable, so there must be some use-case for this.

推荐答案

一般来说,没有,你不应该将其更改为一个结构。只是因为它是不可变的,并不意味着它会自动的,作为一个结构的好人选。

Generally, no, you should not change it to a struct. Just because it's immutable doesn't mean that it's automatically a good candidate for being a struct.

一个结构应该是很小的。随着四位整数它只是在那里的表现结构开始下降16个字节的建议的限制。

A struct should be small. With your four ints it's just at the recommended limit of 16 bytes where performance for structs starts to degrade.

一个结构应该代表某种单一的实体。也许你的类确实如此,但是从你的描述它不容易发出声音。

A struct should represent a single entity of some kind. Perhaps your class does that, but from your description it doesn't sound likely.

一个结构是难以正确实现不是类。它应该表现很好的事情喜欢攀比,所以有更多的东西比什么是预期的类来实现。

A structure is harder to implement correctly than a class. It should behave well to things like comparisons, so there are more things to implement than what is expected of a class.

除非你有一个很好的理由来实现它作为一个结构,一样的性能问题,你应该让你的类为一类。

Unless you have a really good reason to implement it as a struct, like performance issues, you should keep your class as a class.

这篇关于不可变类VS永恒结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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