Temporarily change the value of a variable

In the implementation of the API in which I am hacking now, there is a need to repeatedly change some variables temporarily before performing any task, and change them after completing the task to what it was before.

The current code is as follows:

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

To do this a lot, it is annoying, ugly, difficult to maintain and bury real algorithms under a big mess, which are only implementation artifacts.

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

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

When I tried to do something like this in C #, I failed , because, apparently, C # could not store references to other objects in classes .

, #, ?

P.S.: , , , . .

+5
3

, , Lamda?

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

:

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

:

, doit , . DoSomething. { DoSomething(); }. :

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

, , , , . , , , . , .

, , , . , :

class Frobber
{
    State state;
    ...
    void M()
    {
         ...
         try
         {
             oldstate = state;
             state = newstate;
             this.DoIt();
         }
         finally
         {
             state = oldstate;
         }
    }

:

class Frobber
{
    State state;
    ...
    void M()
    {
         ...
         Frobber newFrobber = new Frobber(newstate);
         newFrobber.DoIt();
         ...

, , . , . , .

+6

, , . SharePoint , , .

, cahnge using. using - - contentios, , :

:

using(TemporaryChange(true, myValue, v => myValue = v))
{
 // code to run while "myValue" is changed to "true"
}

:

class TemporaryChange<V> : IDisposable
{
    private V original;
    private Action<V> setValue;

    internal TemporaryChange(V value, V currentValue, Action<V> setValue)
    {
        this.setValue = setValue;
        this.original = currentValue;
        this.setValue(value);
    }

    void IDisposable.Dispose()
    {
        this.setValue(this.original);
    }
}
+6

All Articles