[英]How to ensure a struct with a string array as a field would follow value semantics while assigning to another variable
In MSDN documentation it is mentioned that " Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. " 在MSDN文档中 ,提到了“ 结构是在分配时复制的。将结构分配给新变量时,将复制所有数据,并且对新副本的任何修改都不会更改原始副本的数据。 ”
I have struct which has a string array as the only field inside it. 我有一个具有字符串数组作为其中唯一字段的结构。
struct MyVar
{
private readonly string[] value;
MyVar(string[] iVal)
{
value = iVal;
}
}
When I assign one struct variable to another how to ensure the string array would be copied fully (deep copy) to assigned variable. 当我将一个结构变量分配给另一结构变量时,如何确保将字符串数组完全复制(深拷贝)到分配的变量。
You can't do this in C# because there's no way to intercept the compiler-generated code to copy the struct's data from one to another. 您无法在C#中执行此操作,因为无法拦截编译器生成的代码以将结构的数据从一个复制到另一个。
The only thing you can really do is to make your struct fully immutable. 您唯一能做的就是使您的结构完全不可变。
That means: 这意味着:
That's a lot of limitations. 有很多限制。 The safest way is to never store any mutable reference types in your struct...
最安全的方法是永远不要在您的结构中存储任何可变的引用类型。
Anyway, to make your struct safer you can defensively copy the string array: 无论如何,为了使您的结构更安全,您可以防御性地复制字符串数组:
struct MyVar
{
private readonly string[] value;
MyVar(string[] iVal)
{
value = (string[])iVal.Clone();
}
}
That particular example is now safe to copy because it doesn't have any way for the string array to be mutated. 现在可以安全地复制该特定示例,因为它无法更改字符串数组。 But as soon as you add any mutator methods or expose the string array via a property, or pass it to anything that might mutate it, you're back to square one.
但是,一旦您添加了任何mutator方法或通过属性公开了字符串数组,或者将其传递给可能对其进行变异的任何东西,您就会回到平方。
If you want to make a "manual" copy of your struct though, you can do that via serialization. 但是,如果要为结构创建“手动”副本,则可以通过序列化来实现。
It's just that you can't do anything about: 只是您无能为力:
MyVar var1 = new MyVar(test);
MyVar var2 = var1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.