是否使用动态创建的控件重复Lambda代码? [英] Is Lambda code repeated with dynamically created controls?

查看:90
本文介绍了是否使用动态创建的控件重复Lambda代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我回答了问题,基本上是关于UI交互的。但是后来,我想起了OP用其代码处理动态创建的控件的方式。

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.

在.Net 2-4上错过了,现在才了解新东西,实际上就是让我成为第一要务的问题。.

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);
}

在一个测试案例中,这个问题几乎无关紧要;但是代码块可以很容易地变得越来越大。甚至在像Go这样的游戏中,最终也会有成百上千的游戏作品。

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?

推荐答案

每个lambda在编译时都会转换为正常方法,因此不会复制lambas的实际代码。但是,每次运行此方法时,都将实例化引用该代码的新EventHandler委托。

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.

这篇关于是否使用动态创建的控件重复Lambda代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆