.NET Collection是一个结构 [英] .NET Collection that is a struct
问题描述
这是一个有趣的问题……在.net框架中是否有一个是结构的集合?
Here's an interesting question ... is there a collection that is a struct somewhere in the .net framework?
请澄清一下,即使将通用参数设置为值类型,所有现有集合(列表,数组等)也都是引用类型.但是我想知道是否有一种方法可以使实际上是结构的集合成为可能.我显然不打算将其传递出去(这将导致大量复制)……我会将其保留为班级(内部状态)中的私有成员,因此仅定义了一次.我的想法是,我可以避免仅仅为了进行小规模的收集而调用垃圾收集器(想想XNA).
Just to clarify, all of the existing collections (List, array, etc.) are all reference types ... even if you set the generic parameter to a value type. But I want to know if there's a way I can make a collection that is actually a struct. I obviously wouldn't plan on passing this around (which would result in a ton of copying) ... I'd keep it as a private member in my class (internal state) so it's only defined once. The idea is that I would be able to avoid invoking the garbage collector just to make a small collection (think XNA).
假设不存在,那么问题的第二部分是,什么是理想的数据结构?链表?
Assuming one does not exist, a secondary part of the question is, what would be the ideal data structure for this. linked list?
推荐答案
不,这种类型不存在,也不是一个好主意.根据Microsoft准则,结构应该是小的不可变值类型.
No, such a type does not exist and it would not be a good idea. Structs should be small immutable value types according to the Microsoft guidelines.
从值类型使用准则:
- 就像原始类型一样.
- 实例大小不得超过16个字节.
- 是一成不变的.
- 值语义是可取的.
将链表实现为值类型将很困难,因为链表通常是递归定义的.效果很好:
It would be difficult to implement a linked list as a value type because linked lists are typically defined recursively. This works fine:
class Node<T>
{
public T Value;
public Node<T> Next;
}
但这失败了,因为结构具有固定的大小,并且在定义结构时必须知道该大小:
But this fails because structs have a fixed size and that size must be known when the struct is defined:
struct Node<T>
{
public T Value;
// Error: Struct member 'Node<T>.Next' of type 'Node<T>'
// causes a cycle in the struct layout
public Node<T> Next;
}
这篇关于.NET Collection是一个结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!