简体   繁体   中英

How to set a property statically with changing variable

This is probably an easy question, I'm pretty new to OOP in general.

If I have a simple class with one int array property (and constructor)

public class MyClass
{
  public int[] MyProperty {get; set;}
  public MyClass(){}
}

How do I set the property value to the value of an object without the property changing whenever the object does?

MyClass C1 = new MyClass();
MYClass C2 = new MyClass();
int[] x = new int[3] {1,2,3};
C1.MyProperty = x;
x[2] = 7;       //this changes C1.MyProperty to a value of {1,2,7}
C2.MyProperty = x;

I would like the 2 index of the property of C1 to remain a value of 3 even when I change the value of x[2]. Similarly I would like C2 property index 2 value to always be 7. Is there some kind of way i can set the property to something like ValueOf(x)? Do i need some sort of static keyword?

This line:

C1.MyProperty = x;

means that MyProperty is pointing to the same reference as x , so any change in elements of x is visible to your property as well. The code is currently doing shallow copying.

A simple fix could be:

C1.MyProperty = x.ToArray();

ToArray will create a new array/a new reference and assign it to MyProperty .

You should look for deep copying objects .

You might want to Clone (shallow copy) the array.

C1.MyProperty = (int[]) x.Clone();

You get a new array with original values or references, but any new slot assignments will be in the new array.

x.ToArray()

is semantically equivalent, and may be preferred since it is typed and doesn't require the cast.

Try the code below. Right now, you assign the very same array to both fields. If you want separate arrays, you'll need to create a new one every time.

Do note your variable x holds the address of an array, not the array itself. Each an every time you assing a New array to x , you create an array somewhere in the memory and place it's address in x .

I strongly suggest you read about pointers , that's what it's all about.

MyClass C1 = new MyClass();
MYClass C2 = new MyClass();
int[] x = new int[3] {1,2,3};

C1.MyProperty = x;
x[2] = 7;       

x = new int[3] {1,2,3};
C2.MyProperty = x; 
//You know have two arrays, {1,2,7} and {1,2,3}, which are accessible through C1 and C2

EDIT: If you're having a hard time understanding the above, look at the constructor below. I think it is much MUCH easier to understand you get two different arrays here.

If you do understand there are two different arrays here, you should be able to figure out you'll get two different arrays with the code up there.

public class MyClass
{
  public int[] MyProperty {get; set;}
  public MyClass(){
      MyProperty = new int[3] {1,2,3};
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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