C#=>带有参数的Lambda表达式在这种特殊情况下似乎过流/无意义

msf*_*boy 1 c# lambda expression

这就是我现在拥有的:

SetText是WPF中Extended Toolkit RichTextbox的一种方法

public void SetText(FlowDocument document, string text)
{   
    Action<FlowDocument,string> action = SetUIText;
    Dispatcher.CurrentDispatcher.BeginInvoke(action,DispatcherPriority.Background, document, text);
}

private void SetUIText(FlowDocument doc, string text)
{
    TextRange tr = new TextRange(doc.ContentStart, doc.ContentEnd);
    using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(text)))
    {
        tr.Load(ms, DataFormats.Rtf);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不想只是将一个额外的SetUIText方法分配给调度程序的委托.

所以我介绍了lambda表达式:

public void SetText(FlowDocument document, string text)
{
    Action<FlowDocument, string> action;

    action = ( doc, txt) =>
    {
        TextRange tr = new TextRange(document.ContentStart, document.ContentEnd);
        using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(text)))
        {
            tr.Load(ms, DataFormats.Rtf);
        }
    };

    Dispatcher.CurrentDispatcher.BeginInvoke(action,DispatcherPriority.Background, document, text);
}
Run Code Online (Sandbox Code Playgroud)

只需检查lambda的doc,txt参数即可.两个参数都没有使用.我使用的是lambda表达式中的文档和文本.

我可以使用doc OR document AND txt OR text.这个lambda表达式是否值得使用它?我应该坚持我的前两种方法吗?

Jon*_*eet 5

我同意CodeInChaos的评论:你为什么要为采取两个参数的行动而烦恼?我会用这个:

public void SetText(FlowDocument document, string text)
{
    Action action = () =>
    {
        TextRange tr = new TextRange(document.ContentStart,
                                              document.ContentEnd);
        using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(text)))
        {
            tr.Load(ms, DataFormats.Rtf);
        }
    };

    Dispatcher.CurrentDispatcher.BeginInvoke(action,
                                             DispatcherPriority.Background);
}
Run Code Online (Sandbox Code Playgroud)

请注意,您可以使用匿名方法执行相同操作,这甚至可能看起来更自然,因为您甚至可以避免编写空参数列表:

Action action = delegate
{
    TextRange tr = new TextRange(document.ContentStart,
                                          document.ContentEnd);
    using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(text)))
    {
        tr.Load(ms, DataFormats.Rtf);
    }
};
Run Code Online (Sandbox Code Playgroud)