我什么时候应该使用结构而不是类? [英] When should I use a struct instead of a class?

查看:41
本文介绍了我什么时候应该使用结构而不是类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN 说当你需要轻量级对象时你应该使用结构体.结构优于类时还有其他情况吗?

MSDN says that you should use structs when you need lightweight objects. Are there any other scenarios when a struct is preferable over a class?

有些人可能已经忘记了:

Some people might have forgotten that:

  1. 结构可以有方法.
  2. 结构不能被继承.
  1. structs can have methods.
  2. structs cannot be inherited.

我了解结构体和类之间的技术差异,只是我不太清楚何时使用结构体.

I understand the technical differences between structs and classes, I just don't have a good feel for when to use a struct.

推荐答案

MSDN 有答案:在类和结构之间进行选择.

基本上,该页面为您提供了一个 4 项清单,并说除非您的类型符合所有标准,否则请使用类.

Basically, that page gives you a 4-item checklist and says to use a class unless your type meets all of the criteria.

不要定义结构,除非类型具有以下所有内容特点:

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

  • 它在逻辑上代表一个单一的值,类似于原始类型(整数、双精度等).
  • 它的实例大小小于 16 字节.
  • 它是不可变的.
  • 不必经常装箱.

这篇关于我什么时候应该使用结构而不是类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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