通过事件处理程序发送参数?
所以我实际上并不是发送参数,而是将类变量设置为某个值,然后在另一个方法中再次使用它。这是做事的“最佳实践”方式吗?如果没有,我有兴趣学习正确的方法。谢谢!参数可以/应该以其他方式发送吗?
private string PrintThis;
public void PrintIt(string input){
PrintThis = input; //SETTING PrintThis HERE
static private PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintDocument_PrintSomething);
pd.Print();
}
private void PrintDocument_PrintSomething(Object sender, PrintPageEventArgs e) {
e.Graphics.DrawString(PrintThis, new Font("Courier New", 12), Brushes.Black, 0, 0);
//USING PrintThis IN THE ABOVE LINE
}
So I'm not actually sending arguments, but setting a class variable to a certain value, then using it again in another method. Is this the "best practice" way to do things? If not, I'd be interested in learning the correct way. Thanks! Can/Should the arguments be sent some other way?
private string PrintThis;
public void PrintIt(string input){
PrintThis = input; //SETTING PrintThis HERE
static private PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintDocument_PrintSomething);
pd.Print();
}
private void PrintDocument_PrintSomething(Object sender, PrintPageEventArgs e) {
e.Graphics.DrawString(PrintThis, new Font("Courier New", 12), Brushes.Black, 0, 0);
//USING PrintThis IN THE ABOVE LINE
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
闭包被引入到语言中来解决这个问题。
通过捕获适当的变量,您可以为其提供比包含方法“寿命更长”的存储空间:
请注意,这是一个非常方便的功能;编译器代表您解决此问题的方式与您自己的现有解决方案非常相似。 (存在某些差异,例如捕获的变量最终作为某个其他(生成的)类的新创建对象的字段。您现有的解决方案不会执行此操作:您有一个< /em> 类的每个实例的“临时”存储位置,而不是每个
PrintIt
的调用,这不好 - 它不是例如,线程安全)Closures were introduced into the language to solve this very problem.
By capturing the appropriate variable, you can give it storage that 'outlives' the containing method:
Do note that this very much a convenience feature; the way the compiler solves this problem on your behalf is suspiciously similar to your own, existing solution. (There are certain differences, e.g. the captured variable ends up as a field of a newly created object of some other (generated) class. Your existing solution does not do this: you have one 'temporary' storage location per instance of your class rather than per call to
PrintIt
, which is not good - it isn't thread-safe, for example)通常不会,但对于此 API(WinForms 打印)来说,这是常用方法。
考虑一下 PrintThis 不仅仅是一个变量,而且是您的“模型”或“文档”。
Not normally, but for this API (WinForms printing) it is the usual approach.
Consider that PrintThis is not just a variable but your "model" or "document".
或者,您可以使用继承:
Alternatively, you can use inheritance: