Store link in another variable

I searched a bit, but I cannot find a way to save the link to another variable in a specific variable. I am trying to make a class to undo the actions made by the user;

class UndoAction
{
    public object var;
    public object val;
    public UndoAction(ref object var, object val)
    {
        this.var = var;
        this.val = val;
    }

    public static List<UndoAction> history = new List<UndoAction>();
    public static void AddHistory(ref object var, object val)
    {
        history.Add(new UndoAction(ref var, val));
    }
}

I think you can see what I'm trying to achieve here.

The problem I am facing is

this.var = var;

does not store the link, but the value of the reference 'var'. How can I save the link, so I can just run;

this.var = val;

"cancel" action, in my case?

+5
source share
3 answers

Standard secure C # does not support this at all. The underlying structure has almost all the necessary concepts, but they are not displayed in C #. But even then, such a link cannot be stored in the field.

, , , . , , , , :

class VarRef<T>
{
    private Func<T> _get;
    private Action<T> _set;

    public VarRef(Func<T> @get, Action<T> @set)
    {
        _get = @get;
        _set = @set;
    }

    public T Value
    {
        get { return _get(); }
        set { _set(value); }
    }
}

:

var myVar = ...
var myVarRef = new VarRef<T>(() => myVar, val => { myVar = val; });

...

myVarRef.Value = "47";
Console.WriteLine(myVar); // writes 47
+8

. /Unboxing , , .

, . .

, ... IUndoable.

, [UnduableProperty] INotifyPropertyChange PropertyChanged. , , , .

, , , .

, , . - .

, ISerializable.

.

+1

# , , .

, , , , .

this.var = var; # <- that actually gets the reference to var, and not clones the object.

, this.var , , .

0
source

All Articles