The name 'str' does not exist in the current context

后端 未结 2 1699
悲哀的现实
悲哀的现实 2020-12-04 01:11

I have declared a class variable in here

void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    if (e.Error == null)
    {
             


        
2条回答
  •  醉酒成梦
    2020-12-04 01:38

    You've almost certainly declared the variable in a method (i.e. as a local variable), instead of directly in the class itself (as an instance variable). For example:

    // Wrong
    class Bad
    {
        void Method1()
        {
            List str = new List();
        }
    
        void Method2()
        {
            foreach (string item in str)
            {
                ...
            }
        }
    }
    
    // Right
    class Good
    {
        private List str = new List();
    
        void Method1()
        {
            str = CreateSomeOtherList();
        }
    
        void Method2()
        {
            foreach (string item in str)
            {
                ...
            }
        }
    }
    

    As a side-note: if you're very new to C#, I would strongly recommend that you stop working on Silverlight temporarily, and write some console apps just to get you going, and to teach you the basics. That way you can focus on C# as a language and the core framework types (text, numbers, collections, I/O for example) and then start coding GUIs later. GUI programming often involves learning a lot more things (threading, XAML, binding etc) and trying to learn everything in one go just makes things harder.

提交回复
热议问题