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

后端 未结 2 1692
悲哀的现实
悲哀的现实 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<string> str = new List<string>();
        }
    
        void Method2()
        {
            foreach (string item in str)
            {
                ...
            }
        }
    }
    
    // Right
    class Good
    {
        private List<string> str = new List<string>();
    
        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.

    0 讨论(0)
  • 2020-12-04 01:49

    It doesn't work because str is not declared in the other variable. It's sscopong problem. Can you pass str as an input to the other function?

    0 讨论(0)
提交回复
热议问题