C#将实例变量复制到相同类的函数中的局部变量 [英] C# Copying instance variable to local variable in functions of same class

查看:114
本文介绍了C#将实例变量复制到相同类的函数中的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在研究一个开源项目中的一些代码,发现很多此类代码:

I have been looking through some code on an open source project recently and found many occurrences of this kind of code:

class SomeClass
{
    private int SomeNumber = 42;

    public ReturnValue UseSomeNumber(...)
    {
        int someNumberCopy = this.SomeNumber;
        if (someNumberCopy > ...)
        {
            // ... do some work with someNumberCopy
        }
        else
        {
            // ... do something else with someNumberCopy
        }
    }
}

复制实例变量真的​​有好处吗?

Is there any real benefit to making a copy of the instance variable?

推荐答案

否,除非您不想更改SomeNumber的值并且打算更新someNumberCopy.就像您要循环次数并要将someNumberCopy减小为零以跟踪计数一样.

No unless you don't want to change the value of SomeNumber and you intend on updating someNumberCopy. Like if you were going to loop the number of times and were going to decrement someNumberCopy down to zero to keep track of the count.

我想复制这样的变量可以保护您免于某些外部函数更改SomeNumber并在执行操作时在您不知情的情况下对其进行更改.如果该类应该在多线程应用程序中使用,我可能会看到这种情况.也许他不是我要解决的方法,但这可能是作者的意图.

I suppose copying the variable like that could protect you from some outside function altering SomeNumber and changing it without your knowledge while performing an operation. I could potentially see this if the class was supposed to be used in a multi-threaded application. Maybe not he way I would go about it, but that could have been the author's intent.

这篇关于C#将实例变量复制到相同类的函数中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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