[英]C# => Lambda expression with parameter seem overfluid/senseless in this special case
这就是我现在所拥有的:
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或document和txt或text。 这个lambda表达式值得使用吗? 我应该坚持前两种方法吗?
我同意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);
}
请注意,您可以使用匿名方法执行相同的操作,这种方法看起来更自然,因为您甚至可以避免编写空的参数列表:
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);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.