Frage

I have an structure and a class

public class MyClass
{
    public string name;
}

public struct MyStructure
{
    public MyClass classValue;
    public int intValue;
    public MyStructure(MyClass classValue, int intValue)
    {
        this.classValue = classValue;
        this.intValue = intValue;
    }
}

Elsewhere I write the following code:

MyClass class1 = new MyClass() { name = "AA" };
MyStructure struct1 = new MyStructure(class1, 4);
MyStructure struct2 = struct1;
struct1.classValue.name = "BB";  //struct2.classValue.name also change!

How can I make sure that every reference type member of a structure is copied by value in cases such as this?

War es hilfreich?

Lösung

Your MyStructure consists of an object reference of type MyClass and an int (Int32). The assignment

MyStructure struct2 = struct1;

copies just those data, the reference and the integer. No new instance of MyClass is created. You can't change that.

If you want to copy, you can say

MyStructure struct2 = new MyStructure(
    new MyClass { name = struct1.classValue, },
    struct1.intValue
    );

Of course, if you need to do this a lot, you can write a Clone() method to do just this. But you will have to remember to use the Clone method and not just assign.

(By the way, the MyStructure is a "mutable struct". Many people discourage them. If you mark the fields of MyStructure as readonly, I think "many people" will be satisfied.)

Addition: See also Answer to Can structs contain references to reference types in C#.

Andere Tipps

The assignment operator will not deep-copy a reference-type field inside of a struct. You can create your own copy constructor that will perform the deep-copy manually, however:

public MyStructure(MyStructure structure)
{
    classValue = new MyClass() { name = structure.classValue.name };
    intValue = structure.intValue;
}

Then call the copy constructor using:

MyStructure struct2 = new MyStructure(struct1);

Alternatively, you could change MyClass to a struct.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top