开发者

C# => Lambda expression with parameter seem overfluid/senseless in this special case

This is what I have now:

SetText is a Method of the Extended Toolkit RichTextbox 开发者_高级运维in WPF

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);
    }
}

I do not want to make an extra SetUIText method just to assign it to the delegate for the dispatcher.

So I introduced the lambda expression:

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);
}

Just check the doc,txt parameter of the lambda. Both parameters are NOT used. What I use instead is document and text inside the lambda expression.

I could use doc OR document AND txt OR text. Is this lambda expression worth at all to use it? Should I stick with my first 2 methods?


I agree with CodeInChaos's comment: Why are you bothering with an action taking two parameters? I would use this:

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);
}

Note that you can do the same with an anonymous method, which may even look more natural, as you can avoid even writing an empty parameter list:

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);
    }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜