C#- using a variable in an 'enclosing' loc

2019-07-28 09:55发布

问题:

I am trying to add some new features to a C# application- in particular, trying to replicate some of its behavior, but inside a web browser, rather than in the application, as it currently is.

I am trying to call a method that has been defined in the Browser.cs class from inside a method in the MainWindow.cs class.

The method is defined in Browser.cs with:

public partial class Browser : Form{
    public Browser(){
        ...
    }
    public void Browser_Load(object sender, EventArgs e){
        webKitBrowser1.Navigate("https://google.com");
    }
    ...
}

I am then trying to call it from MainWindow.cs as follows:

public partial class MainWindow : Window{
    ...
    public MainWindow(){
        ...
        Browser mBrowser = new Browser();
        Object sender = new Object();
        EventArgs e = new EventArgs();
        mBrowser.Browser_Load(sender, e);
        ...
    }
    ...
}

But, I'm getting a compile error that says:

A local or parameter named 'e' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter

What does this mean? I've never come across this error before- I am using the variable inside the same scope as where it has been declared- what does it mean by 'enclosing local scope'? Is that because I'm using e inside the parenthesis for the method call to mBrowser.Browser_Load(sender, e)?

Surely, since the call to this method is inside the same scope as where I've defined e, it shouldn't be an issue of scope?

I did try performing the call with:

mBrowser.Browser_Load(sender, EventArgs e);

but this gave me a compile error saying:

'EventArgs' is a type, which is not valid in the given context.

Can anyone point out what I'm doing wrong here, and what I should be doing to be able to call this method correctly?

回答1:

The error is pretty clear, you have already defined e named variable in your scope, (Probably in the part of code that you haven't shown).

But more importantly, you shouldn't be calling the Load event like that, instead extract the functionality in a separate method and call the method from your Load event and other places.

Like:

public void SomeMethodToBeCalledOnLoad()
{
    webKitBrowser1.Navigate("https://google.com");
}

public void Browser_Load(object sender, EventArgs e)
{
    SomeMethodToBeCalledOnLoad();
}

public MainWindow(){
    ...
    Browser mBrowser = new Browser();
    Object sender = new Object();
    EventArgs e = new EventArgs();
    SomeMethodToBeCalledOnLoad();//here
    ...
}


回答2:

You already have a variable named e in the scope.

try to call your method like this

mBrowser.Browser_Load(this, EventArgs.Empty);

and the error should go.