临时更改变量的值 [英] Temporarily change a variable's value

查看:124
本文介绍了临时更改变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个API实现我目前黑客攻击,有需要反复修改一些变量是暂时的,做一些任务前,并改变它们后面的任务做是为了什么,他们之前后。

In an API implementation I'm currently hacking on, there's the need to repeatedly change some variables temporarily, before doing some task, and change them back after the task is done to whatever they were before.

目前的代码看起来是这样的:

The current code looks like this:

var _oldValue = _variable;
_variable = tempValue;
try
{
  doIt();
}
finally
{
  _variable = oldValue;
}



这样做了很多很烦人,丑陋,难以维护,并埋下了很大的混乱,这只是实现工件的实际算法。

Doing this a lot is annoying, ugly, hard to maintain, and buries the actual algorithms under a lot of clutter that's just implementation artifacts.

在C ++中,我会做施工期间某处存储旧值的一类,并在其析构函数恢复它:

In C++, I would make a class which stores the old value somewhere during construction, and restores it in its destructor:

{
  temp_value tmp(variable_, temp_val);
  do_it();
}

在试图做类似的东西在C#中的I失败因为很明显的C#不能存储在类其他对象的引用。

When trying to do something similar in C# I failed because apparently C# can't store references to other objects in classes.

所以,我将不得不在C#中做删除混乱?

So what would I have to do in C# to remove that clutter?

P.S .:随意添加你认为合适的任何其他标记。我未能拿出任何。

P.S.: Feel free to add any other tags you see fit. I failed to come up with any.

推荐答案

为什么不创建一个会为你的方法,然后传递的Lamda呢?

Why not create a method that does it for you, and then pass a Lamda to it?

private void SaveGlobalsAndDoSomething(Action doit)
{
    var _oldValue = _variable;
    _variable = tempValue;
    try
    {
        doit();
    }
    finally
    {
        _variable = _oldValue;
    }
}

和使用它:

SaveGlobalsAndDoSomething(() => { DoSomething(); });



编辑回应评论:

Edit in response to comment:

DOIT 有时会返回一个值是没有问题的。我们不通过的DoSomething 的方法。我们正在通过 {DoSomething的(); } 的方法。所以,你可以很容易地写:

That doit sometimes returns a value isn't a problem. We're not passing DoSomething to the method. We're passing { DoSomething(); } to the method. So you can easily write:

int returnValue;
SaveGlobalsAndDoSomething(() => { returnValue = DoSomething(); });

这篇关于临时更改变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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