闭包匿名委托 注意点

using System.Windows;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 
    /// 
    public delegate void Test(string a);
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            string str = "aaaaaa";
            Loaded += delegate
            {
                MessageBox.Show(str);
            };
        }
     
    }
}
delegate放法可以直接使用str参数,是因为delegate会动态的copy,MainWindow方法中的参数以及方法外的参数,
所以当delegate在for中的话不要这么写,会动态生成很多遍参数,也会销毁很多遍参数,内存上消耗很大,不要使用。

 

posted on 2018-01-09 13:09  dzh1990  阅读(115)  评论(0编辑  收藏  举报