c# - Sending Arguments Via Event Handler? -


so i'm not sending arguments, setting class variable value, using again in method. "best practice" way things? if not, i'd interested in learning correct way. thanks! can/should arguments sent 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 above line } 

closures introduced language solve problem.

by capturing appropriate variable, can give storage 'outlives' containing method:

// note 'input' variable captured lambda. pd.printpage += (sender, e) => print(e.graphics, input); ...  static void print(graphics g, string input) { ... } 

do note convenience feature; way compiler solves problem on behalf suspiciously similar own, existing solution. (there differences, e.g. captured variable ends field of newly created object of other (generated) class. existing solution not this: have one 'temporary' storage location per instance of class rather per call printit, not - isn't thread-safe, example)


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -