问题
Today I answered a question, basically about UI interaction. But later it got me thinking about the way the OP had hadled the dynamically created controls with their code.
Having missed out on .Net 2-4 and only now learning the 'new' stuff, this actually was what got me into the question in the fist place..:
private void AddPieceButton_Click(object sender, EventArgs e)
{
somePieceControl newPiece = new somePieceControl ();
//..
newPiece.MouseDown += (sender2, evt) => { /* 1st block of code */ };
newPiece.MouseUp += (sender2, evt) => { /* 2nd block of code */ };
newPiece.MouseMove += (sender2, evt) => { /* 3rd block of code */ }
//..
someContainer.Controls.Add(newPiece);
}
In a test case the question hardly matters; but the code blocks can easily get many more and much much larger; also in a game like Go there would eventually be hundreds of game pieces..
While one would/could&should probably question the idea of adding so many controls, inquiring minds still want to know..: Will each piece have its own copy of those code blocks as I guess it has or are they factored out in our world of wonders like normal events and live only once in run-time memory?
回答1:
Each lambda gets converted into a "normal" method at compile time, so the actual code for the lambas will not be duplicated. However, new EventHandler delegates that reference the code will be instantiated every time this method runs.
回答2:
As Michael Liu said, there is no additional memory overhead of using lambdas. But you need to know about closures, which store references to the non-local variables (I mean, in the outer scope of lambda). You can even get a memory leak while using closures.
What about event handlers? You can easily eliminate additional event handlers, by using event routing on the parent element\container (if you're using a XAML-based UI framework).
来源:https://stackoverflow.com/questions/25592562/is-lambda-code-repeated-with-dynamically-created-controls