开发者

Overwriting an object

开发者 https://www.devze.com 2023-03-18 01:04 出处:网络
I have a situation where I get a reference to an object that I would like to \"overwrite\" with another object of the same type. I know by design that the objects are of the same type. I do not have a

I have a situation where I get a reference to an object that I would like to "overwrite" with another object of the same type. I know by design that the objects are of the same type. I do not have access to the parent object in this function.

The dataobject is defines as like:

    Class DataObject
    {
         public List<int> 开发者_Go百科Stuff = new List<int>();
    }

Then there is a method

    void DoStuff(object obj)
    {
         // At this point I know that obj is List<int>
         // Create new object from some source
         var newList = new List<int>();

         // Here I would like to make the passed object the new object
         (the pointer of obj) = (the pointer of newlist)
    }

I don't know if this is possible. It's just something I've been banging my head against for a couple of hours now and my brain seems to have stopped working.

Thanks in advance

Johan


Pass object by reference:

void DoStuff(ref DataObject dataObject)
{
    dataObject = ...;
}

ref object won't be allowed here, however.


You could use the Clone function but take a look at the following Stackoverflow link that has a nice method for cloning objects.


No, it's not possible with your current code - the reference is passed by value, and is thus entirely independent of how you originally accessed it. Even if you changed obj to be a ref parameter, you wouldn't be able to call the method with ref Stuff because the types would be incorrect. You could potentially do it with a generic parameter:

void DoStuff<T>(ref T obj)
{
    object newList = new List<int>();
    obj = (T) newList;
}

That's pretty horrible though.

It's normally a design smell to want to do this - if you can explain more about the bigger picture, we may be able to help more.


obj = newList what difference it will make if pointer of obj is changed to newList or pointer of newList will be changed to obj?

0

精彩评论

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