简体   繁体   English

具有动态字段数的C#值类型

[英]C# value type with dynamic number of fields

The best way to explain my problem is with a code snippet: 解释我的问题的最好方法是使用代码片段:

enum Resource { ..., Size }
class ResourceVector 
{
    int[] values = new int[(int)Resource.Size];

    public static ResourceVector operator + (ResourceVector a, ResourceVector b)
    {...}

    ...
}

We are using this type everywhere as though it were a value type. 我们在任何地方都使用这种类型,就好像它是一种值类型。 Ie we are making the assumption that: 即我们假设:

ResourceVector b = a;
b += c;

will not affect a , because that is how we are used to talking about vectors (and that is how a vector with a fixed number of fields does behave, if implemented as a struct). 不会影响a ,因为这就是我们习惯于讨论向量的方式(这就是具有固定数量字段的向量如何表现的行为,如果实现为结构)。

However since that assumption is wrong, it has led to some extremely subtle bugs. 然而,由于这个假设是错误的,它导致了一些非常微妙的错误。

I am wondering if there is a way to make this behave as a value type, other than just expanding the members of Resource each into their own members in a struct ResourceVector (which requires touching every member of ResourceVector if we wish to add another Resource ). 我想知道是否有办法使这种行为作为一种值类型,而不仅仅是将Resource的成员扩展到struct ResourceVector每个成员(如果我们想要添加另一个Resource ,则需要触及ResourceVector每个成员) 。

Oh, just in case, we are working with C# 2.0. 哦,以防万一,我们正在使用C#2.0。 So no fancy-pants features :-) 所以没有花哨裤特点:-)

Thanks. 谢谢。

I think you are confusing “value type” with “immutable type”. 我认为你将“值类型”与“不可变类型”混为一谈。 You actually want your ResourceVector to be an immutable type . 您实际上希望ResourceVector是不可变类型

An immutable type is one that has no way to change its contents. 不可变类型是无法更改其内容的类型。 Once constructed, an instance retains its value until it is garbage-collected. 构造完成后,实例会保留其值,直到进行垃圾回收。 All operations such as addition return a new instance containing the result instead of modifying an existing instance. 诸如添加之类的所有操作都返回包含结果的新实例 ,而不是修改现有实例。

string is the most well-known immutable class. string是最着名的不可变类。 All operations like Substring and Replace return a new string and don't modify the existing strings. 所有操作(如SubstringReplace返回一个字符串,而不会修改现有字符串。

Once your type is properly immutable, semantically it doesn't matter so much anymore whether it is a value type or a reference type — but it matters to the performance. 一旦你的类型是正确不可变的,从语义上来说,无论它是值类型还是引用类型都无关紧要 - 但它对性能很重要。 If you pass values around a lot, you should probably make it a reference type in order to avoid a lot of unnecessary copying. 如果你传递很多值,你应该把它作为引用类型,以避免大量不必要的复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM