所以我实际上并没有发送参数,而是将类变量设置为某个值,然后在另一个方法中再次使用它。这是做事的“最佳实践”方式吗?如果没有,我会对学习正确的方法感兴趣。谢谢!参数可以/应该以其他方式发送吗?
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
}
最佳答案
Closures被引入语言来解决这个问题。
通过捕获适当的变量,您可以为其提供“比包含方法长寿”的存储空间:
// Note that the 'input' variable is captured by the lambda.
pd.PrintPage += (sender, e) => Print(e.Graphics, input);
...
static void Print(Graphics g, string input) { ... }
请注意,这是一个非常方便的功能;编译器代表您解决此问题的方式与您自己现有的解决方案非常相似。 (存在某些差异,例如,捕获的变量最终作为某个其他(生成的)类的新创建对象的字段。您现有的解决方案不会这样做:您有一个 每个类的实例 的“临时”存储位置,而不是每个 调用 到 PrintIt
,这不好 - 它不是线程安全的,例如)
关于c# - 通过事件处理程序发送参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4971460/