mercredi 31 décembre 2014

How to get a class object to store another class object in c#?

Suppose we have the C# code below that stores an instance of class A in class B. I want to create a version of class B that stores its own A. So when we change A outside of B, the internal A object in B doesn't change.



class A
{
public int data = 9;
}
class B
{
public B(A a_) { a = a_; }
public A a;
}

class Program
{
static void Main(string[] args)
{
A foo = new A();
foo.data = 20; // this changes the field a in B as well
B bar = new B(foo);

Console.WriteLine(bar.a.data); // prints 20 instead of 9
}
}


I can avoid this problem in C++ by using a templated bridge class that clones A when passing A into B. But apparently deep clones doesn't seem as widely used in C# for some reason(why?). Can anyone provide a good way around this storing problem.


C++ code:



template <typename T>
class Wrapper{
public:
Wrapper(const Wrapper<T> &orig){if(orig.data!=nullptr)data = orig.data->clone();}
Wrapper(const T &origdata){data = origdata.clone();}
Wrapper & operator=(const Wrapper<T> &orig){...}
...
~T(){delete data;}
private:
T *data;
}

class A{
public:
A():data(9){}
int data;
A *clone(){return new A(*this);}
}

class B{
public:
B(const Wrapper<A>& a_):ainner(a_){}
Wrapper<A> ainner;
}

int main(){
A a;
B b(a);
a.data =20;
std::cout << b.ainner.data; // prints 9 still
return 0;
}

Aucun commentaire:

Enregistrer un commentaire