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

你说的曾经没有我的故事 提交于 2019-12-20 04:04:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/3950889/do-methods-which-return-reference-types-return-references-or-cloned-copy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!