C#=>在这种特殊情况下,带有参数的 Lambda 表达式似乎过于流动/毫无意义
这就是我现在所拥有的:
SetText 是 WPF 中扩展工具包 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);
}
}
我不想创建一个额外的 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);
}
只需检查lambda的doc,txt参数即可。这两个参数均未使用。我使用的是 lambda 表达式内的文档和文本。
我可以使用 doc 或文档以及 txt 或文本。这个 lambda 表达式值得使用吗?我应该坚持前两种方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我同意 CodeInChaos 的评论:为什么你要为采用两个参数的操作而烦恼?我会使用这个:
请注意,您可以使用匿名方法执行相同的操作,这甚至可能看起来更自然,因为您甚至可以避免编写空参数列表:
I agree with CodeInChaos's comment: Why are you bothering with an action taking two parameters? I would use this:
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: