开发者

Object Reference Problem

开发者 https://www.devze.com 2023-02-21 01:38 出处:网络
I want to create t objects that refers to same reference but I want to change properties in the second one and don\'t change for the first one

I want to create t objects that refers to same reference but I want to change properties in the second one and don't change for the first one

student s=new student(10);

.........

student s2=new student(10);


s2.class="class2"

the question is to how can I know when I am at creating the seond student that I created instance before and if i created one before ,I will create new deep copy to avoid it

my proposal will be

{
student s=new student(10);

.........

if(we create any insatnce before from student)

student s2=cloneStudentMethod(10);
s2.class="class2"

}

and the cloneStudent开发者_如何学GoMethod(10) create one deep copy object

the problem is how can I create this if condition ???

I hope that my problem is clear


One way would be to write a student factory which keeps track of that:

public class StudentFactory
{
    private HashSet<int> _CreatedIds = new HashSet<int>();
    public Student Create(int id)
    {
        _CreatedIds.Add(id);
        return new Student(id);
    }

    public bool HasCreatedStudentBefore(int id)
    {
         return _CreatedIds.Contains(id);
    }
}

Update: Instead of just putting the ids into the hashset you could store the students in there and return a copy of a student object if it is already in there.


You could implement some kind of clone method and do something like:

if (s != null)
{
student s2 = new Student();
s2.Clone(s);
}

This way you are passing the object you want to clone instead of just the single property (10 in your example).

I feel I don't quite understand your question, though.

0

精彩评论

暂无评论...
验证码 换一张
取 消