【问题标题】:The name 'X' does not exist in the current context - C#当前上下文中不存在名称“X”-C#
【发布时间】:2021-03-17 03:07:23
【问题描述】:

我对 C# 相当陌生,所以我怀疑我遗漏了一些明显的东西,但我有一个看起来非常简单的案例,我在 C# 中定义了一个数据表并将一列添加到数据表的 DataColumnCollection。我在智能感知中收到一条错误消息:

名称mytable 在当前上下文中不存在。

我还收到如下所示的编译器错误,我将其解释为试图理解无法识别的 mytable 的结果。

1>\Controllers\OutputControllerdemo.cs(14,28,14,29):错误 CS1519: 类、记录、结构或接口成员中的无效标记 '(' 声明

1>\Controllers\OutputControllerdemo.cs(14,36,14,37):错误 CS8124: 元组必须至少包含两个元素。

1> \Controllers\OutputControllerdemo.cs(14,37,14,38):错误 CS1519: 令牌无效 ';'在类、记录、结构或接口成员中 声明

欣赏您可能拥有的任何见解

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data;

namespace VPopWeb.Controllers
{
    public class OutputControllerdemo : Controller
    {
        DataTable mytable = new DataTable("Results");
        DataColumn column1 = new DataColumn("Date", System.Type.GetType("DateTime"));
        mytable.Columns.Add(column1); //Error Here:  The name mytable does not exist in the current context.
        
        public ViewResult Chart() => View("Chart");
    }
}

【问题讨论】:

  • 该代码(特别是添加列的第三行)需要在方法中。所有过程代码都必须有一个方法作为它的主目录。

标签: c# asp.net-mvc


【解决方案1】:

好的,让我们回顾一下您的代码以及每一行的含义。

这两行声明并分配给两个类字段。没问题。

DataTable mytable = new DataTable("Results");
DataColumn column1 = new DataColumn("Date", System.Type.GetType("DateTime"));

下一行代码没有声明任何东西,也没有分配任何东西。这是一个语句,不能存在于类级别。它必须驻留在函数中。

mytable.Columns.Add(column1);

我相信您对代码的意图如下:

public class OutputControllerdemo : Controller
{
    public ViewResult Chart()
    {
        DataTable mytable = new DataTable("Results");
        DataColumn column1 = new DataColumn("Date", System.Type.GetType("DateTime"));
        mytable.Columns.Add(column1); 
        return View("Chart");
    }
}

mytablecolumn1 的声明一定属于方法吗?不,他们可以存在于班级级别。但是,我相信您打算在创建图表的方法中使用它们,所以我将它们移到了那里。

错误没有直接告诉你这是因为编译器无法推断你的意图,而我们可以做出很好的猜测。

【讨论】:

    【解决方案2】:

    您不能在方法之外编写可执行代码。只能声明字段、属性、事件等。

    您可以通过将可执行代码移动到构造函数或使用字段初始值设定项来完成您想要的操作。

    public class OutputControllerdemo : Controller
    {
        DataTable mytable = new DataTable("Results");
        
        public OutputControllerdemo()
        {
            myTable.Columns.Add(new DataColumn("Date", System.Type.GetType("DateTime")));
    
        }
        
        ///Etc...
    

    或者

    public class OutputControllerdemo : Controller
    {
        DataTable mytable = new DataTable("Results")
        {
            Columns = { new DataColumn("Date", System.Type.GetType("DateTime")) }
        };
        
        //Etc....
    
    }
    

    【讨论】:

    • 谢谢。现在很明显,我看到了答案!
    猜你喜欢
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    相关资源
    最近更新 更多