做这回引用类型返回引用或克隆副本的方法呢? [英] Do methods which return Reference Types return references or cloned copy?

查看:140
本文介绍了做这回引用类型返回引用或克隆副本的方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习Java的这些天,我刚才读的是要小心,不要写存取方法返回引用可变对象这是真的有趣。现在我想知道它是否是同在C#性能及存取方法?或C#已经自动返回克隆拷贝?

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?

感谢。

推荐答案

引用是只是......到存储在内存中的一些对象的引用。除非你明确地编写代码来创建克隆并返回的参考的那个对象,那么你将永远传递绕到同一个实例的引用。

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.

一个愚蠢的例子:

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

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

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



因此​​,可以说这家伙$ 50,000和薪水只是得到了加薪。现在,他的薪水是$ 62,500,他应该得到一个不错的新手表。但是,它很可能是另一个线程本员工对象的引用。这意味着他们也有机会获得薪酬属性,之前可能会改变工资总额高于$ 100,000,如果块运行。

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.

这篇关于做这回引用类型返回引用或克隆副本的方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆