简体   繁体   English

返回引用类型的方法是否返回引用或克隆副本?

[英]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. 这些天来我一直在学习Java,而我读到的只是"Be careful not to write accessor methods that return references to mutable objects" ,这确实很有趣。 And now I am wondering whether it is same for Properties and Accessor methods in C#? 现在,我想知道C#中的Properties和Accessor方法是否相同? Or C# already returns cloned copies automatically? 还是C#已经自动返回克隆的副本?

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. 因此,可以说这个家伙的薪水为$ 50,000,但刚刚加薪。 Now his salary is at $62,500 and he should be getting a nice new watch. 现在他的薪水是62,500美元,他应该会得到一块不错的新表。 However, it is very possible that another Thread has a reference to this Employee object. 但是,另一个线程很可能对此Employee对象进行了引用。 That means they also have access to the Salary property, and could change the salary total above $100,000 before the if block runs. 这意味着他们还可以使用Salary属性,并且可以在if块运行之前将薪金总额更改为$ 100,000以上。

In this awkward scenario, the employee would be getting a promotion and a new office even though the Raise() method was only called once. 在这种尴尬的情况下,即使Raise()方法仅被调用一次,该员工也将获得升职和新办公室。

Silly I know, but demonstrates the point. 我知道这很傻,但是可以说明这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM