简体   繁体   中英

Do methods which return Reference Types return references or cloned copy?

I've been learning Java these days and what I've read just is "Be careful not to write accessor methods that return references to mutable objects" which is really interesting. And now I am wondering whether it is same for Properties and Accessor methods in C#? Or C# already returns cloned copies automatically?

Thanks.

A reference is just that... a reference to some object that is stored in memory. Unless you explictly write code to create a clone and return a reference to that object, then you will always be passing around a reference to the same instance.

The situation it is trying to get you to avoid is handing over an object reference to the caller in which you are dependent on. You have no control over who or what might be changing the state of that object and therefore your class might end up with unpredictable results.

A silly example:

public class Employee
{
    public Salary Salary {get; set;}

    public void GiveRaise()
    {
        Salary.Total *= .25;

        if(Salary.Total > 100000)
        {
            Promote();
            GiveBiggerOffice();
        }
        else
        {
            GiveWatch();
        }
    }
}

So lets say this guy had a salary of $50,000 and just got a raise. Now his salary is at $62,500 and he should be getting a nice new watch. However, it is very possible that another Thread has a reference to this Employee object. That means they also have access to the Salary property, and could change the salary total above $100,000 before the if block runs.

In this awkward scenario, the employee would be getting a promotion and a new office even though the Raise() method was only called once.

Silly I know, but demonstrates the point.

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