【问题标题】:Compiler Error CS0119 - 'Case' is a type, which is not valid in the given context编译器错误 CS0119 - 'Case' 是一种类型,在给定的上下文中无效
【发布时间】:2021-06-11 22:02:15
【问题描述】:

尝试在 for 循环中创建自定义类型 Case 的“case”变量时出现 CS0119 错误。 行 Case case = new Case();

private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable dt = tableCollection[cboSheet.SelectedItem.ToString()];
        
        if (dt != null)
        {
            List<Case> cases = new List<Case>();
            
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Case case = new Case();
                


            }
        }
    }

当我重命名变量时,错误就会消失(例如,改为 case1)。 你知道为什么会这样吗?

案例分类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SLACasesImport
{
    public class Case
    {
        public string FacetsID { get; set; }
        public int Comp { get; set; }
        public string Priority { get; set; }
        public DateTime Opened { get; set; }
        public DateTime Closed { get; set; }
        public string Title { get; set; }
        public DateTime ActStart { get; set; }
        public DateTime ActEnd { get; set; }
        public string Hosted { get; set; }
        public string Sustain { get; set; }
        public DateTime ImportDate { get; set; }
    }
}

【问题讨论】:

  • case 是一个关键字。试试@case

标签: c# winforms variables


【解决方案1】:

出现该消息是因为 case 是来自 switch-case 语句的关键字。该消息的性质是编译器/IDE 期望它在 switch case 语句的上下文中,因为您使用的是关键字。

例如,如果您尝试将变量命名为 int,您将得到 Error CS0029: Cannot implicitly convert type 'SLACasesImport.Case' to 'int'

有趣的是,您甚至可以在示例代码中将其作为关键字的性质来判断,因为 StackOverflow 正在突出显示它。

当以@ 开头时,C# 允许像这样的特殊变量名。喜欢@case@int。虽然完全使用不同的名称通常更方便。

【讨论】:

  • “有趣的是,您甚至可以在示例代码中将其作为关键字的性质,因为 StackOverflow 正在突出显示它。”这不是真的。该网站使用的代码突出显示是一个粗略的近似,特别是它无法区分上下文关键字是否实际上是在它们是关键字的上下文中。
  • @Servy 这是评论的重点。有些语言不介意变量名是否与关键字相同。 C# 不是其中之一。所以 StackOverflows 无法区分和突出显示 case 在这里工作。
  • 许多关键字可以用作变量名,特别是上下文关键字。如果您有一个名为 asyncawaitgetgroup 的变量,它们都可以正常工作,但是 SO 会将它们突出显示为关键字,因为它不够聪明,无法意识到它们没有用于使它们成为关键字的上下文。
  • 非常感谢!我还在学习 C#。这就是我所想的。但我希望 VS 会给我更具体的错误消息=)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-07
  • 2020-04-16
  • 2020-07-10
  • 2018-08-09
  • 2016-03-30
  • 2021-01-19
  • 1970-01-01
相关资源
最近更新 更多