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?
MSDN说,当您需要轻量级对象时,应该使用struct。如果结构体优于类,还有其他情况吗?
Edit:
Some people have forgotten that:
1. structs can have methods!
2. structs have no inheritance capabilites.
编辑:有些人已经忘记了:1。结构体可以有方法!2。结构没有继承能力。
Another Edit:
I understand the technical differences, I just don't have a good feel for WHEN to use a struct.
另一个编辑:我理解技术上的差异,只是不太喜欢什么时候使用结构体。
14 个解决方案
#1
281
MSDN has the answer: Choosing Between Classes and Structures.
MSDN有一个答案:在类和结构之间进行选择。
Basically, that page gives you a 4-item checklist and says to use a class unless your type meets all of the criteria.
基本上,这个页面会给你一个4个条目的清单,并告诉你使用一个类,除非你的类型符合所有的标准。
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.
- 它的实例大小小于16字节。
- It is immutable.
- 它是不可变的。
- It will not have to be boxed frequently.
- 它不必经常被装箱。
#2
51
I am surprised I have not read at any of the previous answer this, which I consider the most crucial aspect :
我感到奇怪的是,我没有读过以前的任何回答,我认为这是最重要的方面:
I use structs when I want a type with no identity. For example a 3D point:
当我想要一个没有标识的类型时,我使用struct。例如3D点:
public struct ThreeDimensionalPoint
{
public readonly int X, Y, Z;
public ThreeDimensionalPoint(int x, int y, int z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
public override string ToString()
{
return "(X=" + this.X + ", Y=" + this.Y + ", Z=" + this.Z + ")";
}
public override int GetHashCode()
{
return (this.X + 2) ^ (this.Y + 2) ^ (this.Z + 2);
}
public override bool Equals(object obj)
{
if (!(obj is ThreeDimensionalPoint))
return false;
ThreeDimensionalPoint other = (ThreeDimensionalPoint)obj;
return this == other;
}
public static bool operator ==(ThreeDimensionalPoint p1, ThreeDimensionalPoint p2)
{
return p1.X == p2.X && p1.Y == p2.Y && p1.Z == p2.Z;
}
public static bool operator !=(ThreeDimensionalPoint p1, ThreeDimensionalPoint p2)
{
return !(p1 == p2);
}
}
If you have two instances of this struct you don't care if they are a single piece of data in memory or two. You just care about the value(s) they hold.
如果这个结构体有两个实例,那么就不关心它们是内存中的一个或两个数据片段。你只关心它们的价值。
#3
25
Bill Wagner has a chapter about this in his book "effective c#" (http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660). He concludes by using the following principle:
比尔·瓦格纳(Bill Wagner)在他的《有效的c#》(http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660)一书中有一章是关于这一点的。他的结论是:
- Is the main responsability 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?
- 你确定你的类型永远不会被多形态治疗吗?
If you answer 'yes' to all 4 questions: use a struct. Otherwise, use a class.
如果你对所有四个问题的回答都是“是”,使用结构体。否则,使用一个类。
#4
14
Use a struct when you want value-type semantics instead of reference-type. Structs are copy-by-value so be careful!
当需要值类型语义而不是引用类型时,请使用struct。结构是按值复制的,所以要小心!
Also see previous questions, e.g.
也可以看看前面的问题,例如。
What's the difference between struct and class in .NET?
在。net中,struct和class的区别是什么?
#5
8
I would use structs when:
当:
-
an object is supposed to be read only(every time you pass/assign a struct it gets copied). Read only objects are great when it comes to multithreaded processing as they don't requite locking in most cases.
一个对象应该是只读的(每次您传递/分配一个struct时,它会被复制)。当涉及到多线程处理时,只读对象是很好的,因为它们在大多数情况下不需要锁定。
-
an object is small and short-living. In such a case there is a good chance that the object will be allocated on the stack which is much more efficient than putting it on the managed heap. What is more the memory allocated by the object will be freed as soon as it goes outside its scope. In other words it's less work for Garbage Collector and the memory is used more efficient.
一个物体很小,寿命很短。在这种情况下,很可能会在堆栈上分配对象,这比将其放在托管堆上要有效得多。更重要的是,对象分配的内存一旦超出其范围就会被释放。换句话说,垃圾收集器的工作更少,内存的使用效率更高。
#6
5
I have always used a struct when I wanted to group together a few values for passing things back from a method call, but I won't need to use it for anything after I have read those values. Just as a way to keep things clean. I tend to view things in a struct as "throwaway" and things in a class as more useful and "functional"
当我想要将一些值分组以从方法调用中传递东西时,我总是使用struct,但是在读取完这些值之后,我不需要将它用于任何事情。这是保持清洁的一种方式。我倾向于把结构中的东西看成是“一次性的”,而在课堂上的东西更有用,更“实用”
#7
5
Use a class if:
使用一个类:
- Its identity is important. Structures get copied implicitly when being passed by value into a method.
- 其身份是很重要的。当值传递给方法时,结构会被隐式复制。
- It will have a large memory footprint.
- 它将占用大量内存。
- Its fields need initializers.
- 它的字段需要初始化。
- You need to inherit from a base class.
- 您需要从基类继承。
- You need polymorphic behavior;
- 你需要多态行为;
Use a structure if:
使用一个结构:
- It will act like a primitive type (int, long, byte, etc.).
- 它将表现为基本类型(int、long、byte等)。
- It must have a small memory footprint.
- 它必须有一个小的内存占用。
- You are calling a P/Invoke method that requires a structure to be passed in by value.
- 您正在调用一个P/Invoke方法,该方法要求按值传递结构。
- You need to reduce the impact of garbage collection on application performance.
- 您需要减少垃圾收集对应用程序性能的影响。
- Its fields need to be initialized only to their default values. This value would be zero for numeric types, false for Boolean types, and null for reference types.
- Note that in C# 6.0 structs can have a default constructor that can be used to initialize the struct’s fields to nondefault values.
- 注意,在c# 6.0 struct中,可以使用一个默认构造函数将struct的字段初始化为非默认值。
- 它的字段只需要初始化为它们的默认值。这个值对于数字类型为0,对于布尔类型为false,对于引用类型为null。注意,在c# 6.0 struct中,可以使用一个默认构造函数将struct的字段初始化为非默认值。
- You do not need to inherit from a base class (other than ValueType, from which all structs inherit).
- 您不需要从基类继承(除了ValueType之外,所有结构都继承这个基类)。
- You do not need polymorphic behavior.
- 不需要多态行为。
#8
4
If an entity is going to be immutable, the question of whether to use a struct or a class will generally be one of performance rather than semantics. On a 32/64-bit system, class references require 4/8 bytes to store, regardless of the amount of information in the class; copying a class reference will require copying 4/8 bytes. On the other hand, every distinct class instance will have 8/16 bytes of overhead in addition to the information it holds and the memory cost of the references to it. Suppose one wants an array of 500 entities, each holding four 32-bit integers. If the entity is a structure type, the array will require 8,000 bytes regardless of whether all 500 entities are all identical, all different, or somewhere between. If the entity is a class type, the array of 500 references will take 4,000 bytes. If those references all point to different objects, the objects would require an additional 24 bytes each (12,000 bytes for all 500), a total of 16,000 bytes--twice the storage cost of a struct type. On the other hand, of the code created one object instance and then copied a reference to all 500 array slots, the total cost would be 24 bytes for that instance and 4,000 for the array--a total of 4,024 bytes. A major savings. Few situations would work out as well as the last one, but in some cases it may be possible to copy some references to enough array slots to make such sharing worthwhile.
如果一个实体是不可变的,那么是否使用结构体或类的问题通常是性能问题,而不是语义问题。在32/64位系统上,类引用需要4/8字节来存储,而不考虑类中的信息量;复制类引用需要复制4/8字节。另一方面,每个不同的类实例除了包含的信息和引用的内存成本外,还有8/16字节的开销。假设需要一个500个实体的数组,每个实体持有4个32位整数。如果实体是结构类型,那么无论所有500个实体都是相同的、不同的还是介于两者之间的,数组都需要8000字节。如果实体是类类型,500个引用的数组将占用4000字节。如果这些引用都指向不同的对象,那么对象将需要额外的24字节(所有500个字节为12,000字节),总计16000字节——是struct类型存储成本的两倍。另一方面,在创建一个对象实例并将引用复制到所有500个数组槽中的代码中,该实例的总开销为24字节,数组的总开销为4000字节——总共4,024字节。一个主要的储蓄。很少有情况能像最后一种那样顺利,但在某些情况下,可能可以将一些引用复制到足够多的数组槽中,从而使这种共享有价值。
If the entity is supposed to be mutable, the question of whether to use a class or struct is in some ways easier. Assume "Thing" is either a struct or class which has an integer field called x, and one does the following code:
如果实体应该是可变的,那么在某些方面,是否使用类或结构的问题要容易得多。假设“Thing”是一个结构体或类,具有一个名为x的整数字段,其中一个执行以下代码:
Thing t1,t2; ... t2 = t1; t2.x = 5;
Does one want the latter statement to affect t1.x?
是否希望后面的语句影响t1.x?
If Thing is a class type, t1 and t2 will be equivalent, meaning t1.x and t2.x will also be equivalent. Thus, the second statement will affect t1.x. If Thing is a structure type, t1 and t2 will be different instances, meaning t1.x and t2.x will refer to different integers. Thus, the second statement will not affect t1.x.
如果是类类型,t1和t2是等价的,意味着t1。x和t2。x也是等价的。因此,第二个语句将影响t1.x。如果是结构类型,t1和t2是不同的实例,意味着t1。x和t2。x表示不同的整数。因此,第二个语句不会影响t1.x。
Mutable structures and mutable classes have fundamentally different behaviors, though .net has some quirks in its handling of struct mutations. If one wants value-type behavior (meaning that "t2=t1" will copy the data from t1 to t2 while leaving t1 and t2 as distinct instances), and if one can live with the quirks in .net's handling of value types, use a structure. If one wants value-type semantics but .net's quirks would cause lead to broken value-type semantics in one's application, use a class and mumble.
可变结构和可变类具有根本不同的行为,尽管.net在处理结构突变方面有一些怪癖。如果一个人想要的是值类型的行为(意味着“t2=t1”将从t1到t2的数据复制,而t1和t2则是不同的实例),如果一个人可以在。net的值类型处理中使用这个特性,那么就使用一个结构。如果你想要值类型语义,但是。net的怪癖会导致你的应用程序中值类型语义被破坏,那就使用一个类并含糊不清。
#9
3
In addition the the excellent answers above:
此外,以上的优秀答案:
Structures are value types.
结构是值类型。
They can never be set to Nothing.
他们永远不会一无所有。
Setting a structure = Nothing , will set all its values types to their default values.
设置结构= Nothing,将其所有值类型设置为其默认值。
#10
2
when you don't really need behavior, but you need more structure than a simple array or dictionary.
当您不需要行为时,但是您需要比简单数组或字典更多的结构。
Follow up This is how I think of structs in general. I know they can have methods, but I like keeping that overall mental distinction.
这是我对结构的一般看法。我知道他们可以有方法,但我喜欢保持整体的精神区别。
#11
2
As @Simon said, structs provide "value-type" semantics so if you need similar behavior to a built-in data type, use a struct. Since structs are passed by copy you want to make sure they are small in size, about 16 bytes.
正如@Simon所说,structs提供了“值类型”语义,因此如果您需要类似的行为到内置数据类型,请使用struct。由于结构体是通过复制传递的,所以您需要确保它们的大小很小,大约16字节。
#12
1
Hmm...
嗯…
I wouldn't use garbage collection as an argument for/against the use of structs vs classes. The managed heap works much like a stack - creating an object just puts it at the top of the heap, which is almost as fast as allocating on the stack. Additionally, if an object is short-lived and does not survive a GC cycle, deallocation is free as the GC only works with memory that's still accessible. (Search MSDN, there's a series of articles on .NET memory management, I'm just too lazy to go dig for them).
我不会用垃圾收集作为支持/反对使用结构体vs类的论据。托管堆的工作方式非常类似于一个堆栈——创建一个对象只是把它放在堆的顶部,这几乎和在堆栈上分配一样快。此外,如果一个对象是短期的,并且不能在GC周期中生存下来,那么释放分配是免费的,因为GC只处理仍然可访问的内存。(搜索MSDN,有一系列关于。net内存管理的文章,我懒得去挖掘它们)。
Most of the time I use a struct, I wind up kicking myself for doing so, because I later discover that having reference semantics would have made things a bit simpler.
大多数时候,我使用struct时,我都会为此而责备自己,因为我后来发现使用引用语义会使事情变得简单一些。
Anyway, those four points in the MSDN article posted above seems a good guideline.
无论如何,上面发表的MSDN文章中的四点似乎是一个很好的指导方针。
#13
1
Structs are on the Stack not the Heap so therefore they are thread safe, and should be used when implementing the transfer object pattern, you never want to use objects on the Heap they are volatile, you want in this case to use the Call Stack, this is a basic case for using a struct I am surprised by all the way out answers here,
结构是在堆栈上不是堆因此他们是线程安全的,实现传输对象时,应该使用模式中,您不想使用对象在堆上他们是不稳定,想要在这种情况下使用调用堆栈,这是一个基本的使用结构体我惊讶的答案,
#14
-2
I think the best answer is simply to use struct when what you need is a collection of properties, class when it's a collection of properties AND behaviors.
我认为最好的答案就是使用struct当你需要的是属性集合时,类是属性和行为集合时。
#1
281
MSDN has the answer: Choosing Between Classes and Structures.
MSDN有一个答案:在类和结构之间进行选择。
Basically, that page gives you a 4-item checklist and says to use a class unless your type meets all of the criteria.
基本上,这个页面会给你一个4个条目的清单,并告诉你使用一个类,除非你的类型符合所有的标准。
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.
- 它的实例大小小于16字节。
- It is immutable.
- 它是不可变的。
- It will not have to be boxed frequently.
- 它不必经常被装箱。
#2
51
I am surprised I have not read at any of the previous answer this, which I consider the most crucial aspect :
我感到奇怪的是,我没有读过以前的任何回答,我认为这是最重要的方面:
I use structs when I want a type with no identity. For example a 3D point:
当我想要一个没有标识的类型时,我使用struct。例如3D点:
public struct ThreeDimensionalPoint
{
public readonly int X, Y, Z;
public ThreeDimensionalPoint(int x, int y, int z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
public override string ToString()
{
return "(X=" + this.X + ", Y=" + this.Y + ", Z=" + this.Z + ")";
}
public override int GetHashCode()
{
return (this.X + 2) ^ (this.Y + 2) ^ (this.Z + 2);
}
public override bool Equals(object obj)
{
if (!(obj is ThreeDimensionalPoint))
return false;
ThreeDimensionalPoint other = (ThreeDimensionalPoint)obj;
return this == other;
}
public static bool operator ==(ThreeDimensionalPoint p1, ThreeDimensionalPoint p2)
{
return p1.X == p2.X && p1.Y == p2.Y && p1.Z == p2.Z;
}
public static bool operator !=(ThreeDimensionalPoint p1, ThreeDimensionalPoint p2)
{
return !(p1 == p2);
}
}
If you have two instances of this struct you don't care if they are a single piece of data in memory or two. You just care about the value(s) they hold.
如果这个结构体有两个实例,那么就不关心它们是内存中的一个或两个数据片段。你只关心它们的价值。
#3
25
Bill Wagner has a chapter about this in his book "effective c#" (http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660). He concludes by using the following principle:
比尔·瓦格纳(Bill Wagner)在他的《有效的c#》(http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660)一书中有一章是关于这一点的。他的结论是:
- Is the main responsability 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?
- 你确定你的类型永远不会被多形态治疗吗?
If you answer 'yes' to all 4 questions: use a struct. Otherwise, use a class.
如果你对所有四个问题的回答都是“是”,使用结构体。否则,使用一个类。
#4
14
Use a struct when you want value-type semantics instead of reference-type. Structs are copy-by-value so be careful!
当需要值类型语义而不是引用类型时,请使用struct。结构是按值复制的,所以要小心!
Also see previous questions, e.g.
也可以看看前面的问题,例如。
What's the difference between struct and class in .NET?
在。net中,struct和class的区别是什么?
#5
8
I would use structs when:
当:
-
an object is supposed to be read only(every time you pass/assign a struct it gets copied). Read only objects are great when it comes to multithreaded processing as they don't requite locking in most cases.
一个对象应该是只读的(每次您传递/分配一个struct时,它会被复制)。当涉及到多线程处理时,只读对象是很好的,因为它们在大多数情况下不需要锁定。
-
an object is small and short-living. In such a case there is a good chance that the object will be allocated on the stack which is much more efficient than putting it on the managed heap. What is more the memory allocated by the object will be freed as soon as it goes outside its scope. In other words it's less work for Garbage Collector and the memory is used more efficient.
一个物体很小,寿命很短。在这种情况下,很可能会在堆栈上分配对象,这比将其放在托管堆上要有效得多。更重要的是,对象分配的内存一旦超出其范围就会被释放。换句话说,垃圾收集器的工作更少,内存的使用效率更高。
#6
5
I have always used a struct when I wanted to group together a few values for passing things back from a method call, but I won't need to use it for anything after I have read those values. Just as a way to keep things clean. I tend to view things in a struct as "throwaway" and things in a class as more useful and "functional"
当我想要将一些值分组以从方法调用中传递东西时,我总是使用struct,但是在读取完这些值之后,我不需要将它用于任何事情。这是保持清洁的一种方式。我倾向于把结构中的东西看成是“一次性的”,而在课堂上的东西更有用,更“实用”
#7
5
Use a class if:
使用一个类:
- Its identity is important. Structures get copied implicitly when being passed by value into a method.
- 其身份是很重要的。当值传递给方法时,结构会被隐式复制。
- It will have a large memory footprint.
- 它将占用大量内存。
- Its fields need initializers.
- 它的字段需要初始化。
- You need to inherit from a base class.
- 您需要从基类继承。
- You need polymorphic behavior;
- 你需要多态行为;
Use a structure if:
使用一个结构:
- It will act like a primitive type (int, long, byte, etc.).
- 它将表现为基本类型(int、long、byte等)。
- It must have a small memory footprint.
- 它必须有一个小的内存占用。
- You are calling a P/Invoke method that requires a structure to be passed in by value.
- 您正在调用一个P/Invoke方法,该方法要求按值传递结构。
- You need to reduce the impact of garbage collection on application performance.
- 您需要减少垃圾收集对应用程序性能的影响。
- Its fields need to be initialized only to their default values. This value would be zero for numeric types, false for Boolean types, and null for reference types.
- Note that in C# 6.0 structs can have a default constructor that can be used to initialize the struct’s fields to nondefault values.
- 注意,在c# 6.0 struct中,可以使用一个默认构造函数将struct的字段初始化为非默认值。
- 它的字段只需要初始化为它们的默认值。这个值对于数字类型为0,对于布尔类型为false,对于引用类型为null。注意,在c# 6.0 struct中,可以使用一个默认构造函数将struct的字段初始化为非默认值。
- You do not need to inherit from a base class (other than ValueType, from which all structs inherit).
- 您不需要从基类继承(除了ValueType之外,所有结构都继承这个基类)。
- You do not need polymorphic behavior.
- 不需要多态行为。
#8
4
If an entity is going to be immutable, the question of whether to use a struct or a class will generally be one of performance rather than semantics. On a 32/64-bit system, class references require 4/8 bytes to store, regardless of the amount of information in the class; copying a class reference will require copying 4/8 bytes. On the other hand, every distinct class instance will have 8/16 bytes of overhead in addition to the information it holds and the memory cost of the references to it. Suppose one wants an array of 500 entities, each holding four 32-bit integers. If the entity is a structure type, the array will require 8,000 bytes regardless of whether all 500 entities are all identical, all different, or somewhere between. If the entity is a class type, the array of 500 references will take 4,000 bytes. If those references all point to different objects, the objects would require an additional 24 bytes each (12,000 bytes for all 500), a total of 16,000 bytes--twice the storage cost of a struct type. On the other hand, of the code created one object instance and then copied a reference to all 500 array slots, the total cost would be 24 bytes for that instance and 4,000 for the array--a total of 4,024 bytes. A major savings. Few situations would work out as well as the last one, but in some cases it may be possible to copy some references to enough array slots to make such sharing worthwhile.
如果一个实体是不可变的,那么是否使用结构体或类的问题通常是性能问题,而不是语义问题。在32/64位系统上,类引用需要4/8字节来存储,而不考虑类中的信息量;复制类引用需要复制4/8字节。另一方面,每个不同的类实例除了包含的信息和引用的内存成本外,还有8/16字节的开销。假设需要一个500个实体的数组,每个实体持有4个32位整数。如果实体是结构类型,那么无论所有500个实体都是相同的、不同的还是介于两者之间的,数组都需要8000字节。如果实体是类类型,500个引用的数组将占用4000字节。如果这些引用都指向不同的对象,那么对象将需要额外的24字节(所有500个字节为12,000字节),总计16000字节——是struct类型存储成本的两倍。另一方面,在创建一个对象实例并将引用复制到所有500个数组槽中的代码中,该实例的总开销为24字节,数组的总开销为4000字节——总共4,024字节。一个主要的储蓄。很少有情况能像最后一种那样顺利,但在某些情况下,可能可以将一些引用复制到足够多的数组槽中,从而使这种共享有价值。
If the entity is supposed to be mutable, the question of whether to use a class or struct is in some ways easier. Assume "Thing" is either a struct or class which has an integer field called x, and one does the following code:
如果实体应该是可变的,那么在某些方面,是否使用类或结构的问题要容易得多。假设“Thing”是一个结构体或类,具有一个名为x的整数字段,其中一个执行以下代码:
Thing t1,t2; ... t2 = t1; t2.x = 5;
Does one want the latter statement to affect t1.x?
是否希望后面的语句影响t1.x?
If Thing is a class type, t1 and t2 will be equivalent, meaning t1.x and t2.x will also be equivalent. Thus, the second statement will affect t1.x. If Thing is a structure type, t1 and t2 will be different instances, meaning t1.x and t2.x will refer to different integers. Thus, the second statement will not affect t1.x.
如果是类类型,t1和t2是等价的,意味着t1。x和t2。x也是等价的。因此,第二个语句将影响t1.x。如果是结构类型,t1和t2是不同的实例,意味着t1。x和t2。x表示不同的整数。因此,第二个语句不会影响t1.x。
Mutable structures and mutable classes have fundamentally different behaviors, though .net has some quirks in its handling of struct mutations. If one wants value-type behavior (meaning that "t2=t1" will copy the data from t1 to t2 while leaving t1 and t2 as distinct instances), and if one can live with the quirks in .net's handling of value types, use a structure. If one wants value-type semantics but .net's quirks would cause lead to broken value-type semantics in one's application, use a class and mumble.
可变结构和可变类具有根本不同的行为,尽管.net在处理结构突变方面有一些怪癖。如果一个人想要的是值类型的行为(意味着“t2=t1”将从t1到t2的数据复制,而t1和t2则是不同的实例),如果一个人可以在。net的值类型处理中使用这个特性,那么就使用一个结构。如果你想要值类型语义,但是。net的怪癖会导致你的应用程序中值类型语义被破坏,那就使用一个类并含糊不清。
#9
3
In addition the the excellent answers above:
此外,以上的优秀答案:
Structures are value types.
结构是值类型。
They can never be set to Nothing.
他们永远不会一无所有。
Setting a structure = Nothing , will set all its values types to their default values.
设置结构= Nothing,将其所有值类型设置为其默认值。
#10
2
when you don't really need behavior, but you need more structure than a simple array or dictionary.
当您不需要行为时,但是您需要比简单数组或字典更多的结构。
Follow up This is how I think of structs in general. I know they can have methods, but I like keeping that overall mental distinction.
这是我对结构的一般看法。我知道他们可以有方法,但我喜欢保持整体的精神区别。
#11
2
As @Simon said, structs provide "value-type" semantics so if you need similar behavior to a built-in data type, use a struct. Since structs are passed by copy you want to make sure they are small in size, about 16 bytes.
正如@Simon所说,structs提供了“值类型”语义,因此如果您需要类似的行为到内置数据类型,请使用struct。由于结构体是通过复制传递的,所以您需要确保它们的大小很小,大约16字节。
#12
1
Hmm...
嗯…
I wouldn't use garbage collection as an argument for/against the use of structs vs classes. The managed heap works much like a stack - creating an object just puts it at the top of the heap, which is almost as fast as allocating on the stack. Additionally, if an object is short-lived and does not survive a GC cycle, deallocation is free as the GC only works with memory that's still accessible. (Search MSDN, there's a series of articles on .NET memory management, I'm just too lazy to go dig for them).
我不会用垃圾收集作为支持/反对使用结构体vs类的论据。托管堆的工作方式非常类似于一个堆栈——创建一个对象只是把它放在堆的顶部,这几乎和在堆栈上分配一样快。此外,如果一个对象是短期的,并且不能在GC周期中生存下来,那么释放分配是免费的,因为GC只处理仍然可访问的内存。(搜索MSDN,有一系列关于。net内存管理的文章,我懒得去挖掘它们)。
Most of the time I use a struct, I wind up kicking myself for doing so, because I later discover that having reference semantics would have made things a bit simpler.
大多数时候,我使用struct时,我都会为此而责备自己,因为我后来发现使用引用语义会使事情变得简单一些。
Anyway, those four points in the MSDN article posted above seems a good guideline.
无论如何,上面发表的MSDN文章中的四点似乎是一个很好的指导方针。
#13
1
Structs are on the Stack not the Heap so therefore they are thread safe, and should be used when implementing the transfer object pattern, you never want to use objects on the Heap they are volatile, you want in this case to use the Call Stack, this is a basic case for using a struct I am surprised by all the way out answers here,
结构是在堆栈上不是堆因此他们是线程安全的,实现传输对象时,应该使用模式中,您不想使用对象在堆上他们是不稳定,想要在这种情况下使用调用堆栈,这是一个基本的使用结构体我惊讶的答案,
#14
-2
I think the best answer is simply to use struct when what you need is a collection of properties, class when it's a collection of properties AND behaviors.
我认为最好的答案就是使用struct当你需要的是属性集合时,类是属性和行为集合时。