且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当前上下文中不存在名称“str"

更新时间:2023-02-16 15:52:14

你几乎肯定已经在方法中声明了变量(即作为局部变量),而不是直接在类本身中(作为实例变量).例如:

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)
        {
            ...
        }
    }
}

附带说明:如果您对 C# 非常陌生,我强烈建议您暂时停止使用 Silverlight,编写一些控制台应用程序只是为了让您继续前进,并教你基础知识.这样您就可以专注于 C# 作为一种语言和核心框架类型(例如文本、数字、集合、I/O),然后再开始编写 GUI.GUI 编程通常涉及学习更多的东西(线程、XAML、绑定等),并且尝试一次性学习所有东西只会让事情变得更难.

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.