Undo/Redo

T

thanigai

How to implement undo/redo technique in C#? The undo/redo are not only for
text changes, it also support previous action like creation of an object.
 
M

Miha Markic [MVP C#]

Hi,

There is no support for such thing.
You'll have to do it by yourself.
 
M

Max Guernsey

I would agree. The "command pattern," as it's called, is probably what you
will have to use. However, the wiki mentions that you may have an explosion
of Command classes as a problem. Depending on your performance constraints,
you might be better off writing just a few "generic" command classes that
use reflection. So you might try something like:

#region Assumed
public interface ICommand {
void Do();
void Undo();
}
#endregion

#region Example
[Serializable]
public class PropertySetCommand : ICommand {
private object _Instance;
private System.Reflection.PropertyInfo _TargetProperty;
private object _OldValue;
private object _NewValue;
private object[] _Indeces;

public PropertySetCommand(object instance,
System.Reflection.PropertyInfo targetProperty, object oldValue, object
newValue, object[] indeces) {
_Instance = instance;
_TargetProperty = targetProperty;
_OldValue = oldValue;
_NewValue = newValue;
_Indeces = new object[indeces.Length];
Array.Copy(indeces, _Indeces, indeces.Length);
}

#region ICommand Members
public void Do() {
_TargetProperty.SetValue(_Instance, _NewValue, _Indeces);
}

public void Undo() {
_TargetProperty.SetValue(_Instance, _OldValue, _Indeces);
}
#endregion
}
#endregion

I'm not suggesting this as a perfect, or even good, solution. I'm just
saying that if you suddenly found yourself drowning in an endless sea of
slightly different command classes, using reflection might be an option. It
will, almost certainly, come at the expense of either performance or your
budget, though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top