【问题标题】:The name does not exist in the current context?该名称在当前上下文中不存在?
【发布时间】:2014-05-05 02:32:12
【问题描述】:

从今天开始,我就是一个 C# 菜鸟。我找不到一个好的教程或任何东西,可以解决这个明显愚蠢的问题。基本上,我尝试将程序从 Python 翻译成 C#。通常在 Python 中,我在构造函数中定义常量。我到底应该把它们放在c#的哪里?我试图将它们放在构造函数中,然后将它们放在 Main() 中,因为出现了这个错误。但错误仍然存​​在。

static void Main(string[] args)
    {
    var _top = 0
    ...
    }
public string[] topToken()
    {
        if (_top < _tokens.Count())
        { return _tokens[_top];}

【问题讨论】:

  • 您使用的是哪些教程?它们都应该涵盖成员变量。成员变量是 C# 的基础。

标签: c#


【解决方案1】:

将您的代码更改为:

const int _top = 0;

static void Main(string[] args)
    {
    ...
    }
public string[] topToken()
    {
        if (_top < _tokens.Count())
        { return _tokens[_top];}

要使_top 在整个类中都可以访问,您必须将其声明为字段或常量。字段需要实际存储,而常量只需由编译器替换为实际值。正如您将_top 描述为常量一样,我决定将其声明为常量。

如果你需要一个字段而不是常量,你必须声明它static,因为它是在静态方法中访问的:

static int _top = 0;

因为_top 的声明中没有publicprotected,所以它是类私有的。如果您愿意,可以在声明前添加 private,但如果缺少可见性,这将是默认设置。

【讨论】:

    【解决方案2】:

    _topMain 中声明,因此它不会在topToken 方法中可见。它是一个局部变量,仅作用于Main

    为了让你的变量对整个类可见,你需要在任何方法之外声明它们。

    例如:

    public class SomeClass
    {
        public int someVariable; // all methods in SomeClass can see this
    
        public void DoIt() {
          // we can use someVariable here
        }
    }
    

    注意,将 someVariable 设为 public,也意味着 other 我们可以直接访问它。例如:

    SomeClass x = new SomeClass();
    x.someVariable = 42;
    

    如果你想防止这种情况并且只允许方法/属性/等。为了能够看到someVariable 变量,您可以将其声明为私有。

    如果您需要一个公共变量,通常最好这样声明(这是auto-implemented property) 的示例:

    public class SomeClass
    {
        public int SomeVariable { get; set; }
    
        public void DoIt() {
          // we can use SomeVariable here
        }
    }
    

    这个使用

    【讨论】:

    • 好的,我明白了,但是它应该去哪里呢?它必须在整个班级中都可以访问并且也是公开的。
    • 查看我添加的示例,希望对您有所帮助。
    • 好吧,现在可以了,我只是觉得一切都需要在一个方法中,所以我首先尝试将它放在构造函数中。
    • @Adam - 很高兴听到这个消息。
    • 但这意味着我不能只输入var? - 为什么,编译器可以判断它是字符串还是整数?
    【解决方案3】:

    如果您希望 _topMain 方法之外可用,请将其放在此处:

    int _top = 0; //here instead
    static void Main(string[] args)
    {
        ...
    }
    public string[] topToken()
    {
        if (_top < _tokens.Count())
        { return _tokens[_top];}
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多