名称&#39; <名称>&#39;在当前上下文中不存在</name>

时间:2014-10-12 22:18:40

标签: c# scope

我想知道是否有人可以帮助我。我收到的错误是&#34; The name 'client' does not exist in the current context&#34;。这是参考var tradePileResponse = await client.GetTradePileAsync();行,现在我知道它为什么会发生,但我不知道如何解决它。

我正在使用var client = new FutClient();初始化客户端,但我似乎无法在我的所有应用中使用它。

如何在整个应用中提供此实例?我是否需要在其他地方创建新实例?我试着在课后调用它,但它抱怨说&#34; The contextual keyword 'var' may only appear within a local variable declaration&#34;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

            public async void button1_Click(object sender, EventArgs e)
            {
                var client = new FutClient();
                var loginDetails = new LoginDetails(email, password, secret, platform);
                try
                {
                    var loginResponse = await client.LoginAsync(loginDetails);
                    var creditsResponse = await client.GetCreditsAsync();
                    label1.Text = creditsResponse.Credits.ToString();
                }
                catch (Exception ex)
                {
                    this.textBox4.Text = ex.Message;
                    //throw;
                }
            }

            private async void butGetTradepile_Click(object sender, EventArgs e)
            {
                //var client = new FutClient();
                var tradePileResponse = await client.GetTradePileAsync();
                Console.WriteLine(tradePileResponse);
            }

2 个答案:

答案 0 :(得分:0)

您的问题是范围。你在button1_Click(...)方法中声明变量,在方法结束时变量不再存在,因为垃圾收集。因此,当调用另一个方法时,变量不存在。尝试以下方法,而不是使用&#34; var&#34;使用方法返回的实际类型,如string,int,...等等。如果FutClient是一个类,我相信它是,使用&#34; FutClient客户端&#34;。然后将其设置为类的新实例,无论您喜欢什么。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    FutClient client;//<-- declared it here

    public async void button1_Click(object sender, EventArgs e)
    {
        client = new FutClient();// <--I changed this
        var loginDetails = new LoginDetails(email, password, secret, platform);
        try
        {
            var loginResponse = await client.LoginAsync(loginDetails);
            var creditsResponse = await client.GetCreditsAsync();
            label1.Text = creditsResponse.Credits.ToString();
        }
        catch (Exception ex)
        {
            this.textBox4.Text = ex.Message;
            //throw;
        }
    }

    private async void butGetTradepile_Click(object sender, EventArgs e)
    {
        //var client = new FutClient();
        var tradePileResponse = await client.GetTradePileAsync();
        Console.WriteLine(tradePileResponse);
    }
}

答案 1 :(得分:0)

您需要将client的声明移出button1_Click()方法,并将其设为类级属性。

public partial class Form1 : Form
{
    private FutClient _client;

    public Form1()
    {
        InitializeComponent();
        _client = new FutClient();
    }
}

现在,您可以使用_clientbutton1_Click()

中的butGetTradepile_Click()