本文介绍了C# - 将函数存储在列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 Hey Codeproject, 我知道这可能是一个奇怪的。我正在创建自己的自定义控件,而我目前正处于最终可以实现某些功能的阶段。我要添加的功能之一是撤消和重做,现在我以前从未这样做过,当我考虑使用包含委托功能的列表来简化时,我的好奇心变得更好了undo-redo函数。 现在,我不确定委托是否是正确的单词,我几乎要做的是以下内容: Hey Codeproject,I know this might be an odd one. I'm creating my own custom control, and I'm currently at the stage where I can finally impliment some functions. One of the functions I want to add is "undo" and "redo", now I've never done this before, and my curiosity got the better of me when I thought about using a list containing "delegate" functions to make a simple undo-redo function.Now, I'm not sure if delegate is the right word for it, what I'm pretty much trying to do is the following: public List<Delegate> Undo { get; set; } private void SetText(int Index, string String) { Text.Insert(Index, String); } private void RemoveText(index, String){ Undo.Add(SetText(index, string));} 我希望能够在撤销列表中添加函数SetText(Index,String ),然后从函数Undo()中调用它。 I want to be able to add to the "Undo" list the function SetText(Index, "String"), and then call it from the function Undo();. private void UndoFunction() { Undo[Undo.Count - 1](); Undo.Remove(Undo[Undo.Count - 1]); } 有谁知道这样的事情是否可行?我可能只是找到一种解决方法,如果它不是直接可能的,但如果是的话会很棒。 问候, - Eddie 我尝试过: Does anyone know if something like this is possible? I may just find a workaround if it's not directly possible but it would be great if it was.Regards, - EddieWhat I have tried:public List<Delegate> Undo { get; set; } private void SetText(int Index, string String) { Text.Insert(Index, String); } 推荐答案 List<Action> Undo = new List<Action>();Undo.Add(() => SetText(1, "Hello"));Undo.Add(() => SetText(2, "World"));foreach (var u in Undo){ u();} 或者您可以使用接口创建适合不同类型撤消操作的类。这种方法更灵活,因为你可以让不同的类负责不同类型的动作及其自己的参数等。 Or you can use interfaces to create classes that are suited to different types of undo action. This method is more flexible as you can have different classes responsible for different types of action with their own parameters etcpublic interface IUndo{ void Undo();}public class SetTextUndo : IUndo{ public int Index { get; set; } public string Text { get; set; } public void Undo() { Console.WriteLine("Undo for {0} {1}", this.Index, this.Text); }}public class FormattingUndo : IUndo{ public enum FormatTypeEnum { Bold, Italic, Underline } public FormatTypeEnum FormatType { get; set; } public void Undo() { Console.WriteLine("Undo formatting {0}", this.FormatType); }} List<IUndo> Undo = new List<IUndo>();Undo.Add(new SetTextUndo { Index = 1, Text = "Hello" });Undo.Add(new SetTextUndo { Index = 2, Text = "World" });Undo.Add(new FormattingUndo { FormatType = FormattingUndo.FormatTypeEnum.Italic });foreach (var u in Undo){ u.Undo();} 这篇关于C# - 将函数存储在列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-18 23:58