How do I Convert from Anonymous Event Handlers in

2019-03-04 04:25发布

问题:

I have the below example code for a Windows Phone 7 application, and I am trying to convert it to VB.Net as a starting point. The assignments like this:

Loaded += (_, __) => { anonymousMethodBody();}

are failing to convert when I use a C#-to-VB conversion tool. How should those be translated?

public MainPage()
{
    InitializeComponent();

    Loaded += (_, __) =>
        {
            PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
            cam = new VideoCamera();
            cam.Initialized += (___, ____) =>
                {
                    cam.LampEnabled = true;
                    cam.StartRecording();
                };
            vCam.SetSource(cam);

            new Thread(() =>
                {
                    try
                    {
                        var isf = IsolatedStorageFile.GetUserStoreForApplication();

                        var files = isf.GetFileNames();
                        foreach (var file in files)
                        {
                            Debug.WriteLine("Deleting... " + file);
                            isf.DeleteFile(file);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error cleaning up isolated storage: " + ex);
                    }
                }).Start();
        };
}

回答1:

The Loaded event handler is defined in the C# code you posted using a lambda expression. I suppose most VB.NET-C# converters don't handle those very well, since they are relatively new. Try this:

AddHandler Loaded, Sub() 'Pass the Loaded event parameters, I cannot see them in your code
                  'The code inside the big block
                   End Sub

You don't need to call RemoveHandler (read comments below).