通过事件处理程序发送参数?

soo*_*ise 8 c# class-design

所以我实际上并没有发送参数,而是将类变量设置为某个值,然后在另一个方法中再次使用它.这是做事的"最佳实践"方式吗?如果没有,我有兴趣学习正确的方法.谢谢!可以/应该以其他方式发送参数吗?

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
}
Run Code Online (Sandbox Code Playgroud)

Ani*_*Ani 10

闭包被引入到语言中以解决这个问题.

通过捕获适当的变量,您可以为其提供"超出"包含方法的存储:

// 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) { ... }
Run Code Online (Sandbox Code Playgroud)

请注意这是一个非常方便的功能; 编译器代表您解决此问题的方式与您自己的现有解决方案非常相似.(存在一些差异,例如捕获的变量最终会成为某个其他(生成的)类的新创建对象的字段.您现有的解决方案不会这样做:您的类的每个实例都有一个 "临时"存储位置不是每个调用到,这是不好的-它不是线程安全的,例如)PrintIt