【问题标题】:'Employee' is a type, which is not valid in the given context'Employee' 是一种类型,在给定的上下文中无效
【发布时间】:2020-04-16 02:31:59
【问题描述】:

当我尝试在 Visual Studio 中构建代码时,它显示错误为

  1. 'Employee' 是一种类型,在给定的上下文中无效。
  2. 严重性代码描述项目文件行 错误 CS0246 找不到类型或命名空间名称“C1”(您是 缺少 using 指令或程序集引用?)
    SecondC C:\Users\ypoint\source\repos\SecondC\SecondC\Program.cs 36

我是 C# 新手,请帮我解决这个问题。

using System;

public struct Emplyoee
{
    private int _Id;
    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public int ID
    {
        get { return this._Id; }
        set { this._Id = value; }
    }

    public Emplyoee(int Id, string Name)
    {
        this._Id = Id;
        this._name = Name;
    }

    public void PrintDetails()
    {
        Console.WriteLine("Id={0} && Name={1}", this._Id, this._name);
    }
}

public class Program
{ 
    public static void Main()
    {
        Emplyoee C1 = new Emplyoee(101, "Sudharshan");
        C1.PrintDetails();

    }
}

【问题讨论】:

  • 我尝试过使用 vs 2017 c# 3.0,它适用于我并输出 Id=101 && Name=Sudharshan,我认为您的问题来源不同
  • 添加您项目的命名空间块以获得此代码并尝试。

标签: .net visual-studio-2017 c#-3.0


【解决方案1】:

您的类应该在命名空间中定义,例如:

using System;

namespace Organization.Solution.Project // quite a regular way to define a namespace 
{
    public struct Emplyoee
    {
        // ...
    }

    public class Program
    {
        // ...
    }
}

现在 Program 类知道了 Emplyee 结构,因为它们位于同一个命名空间中。不这样做意味着您的课程在global namespace 中。

为了使代码文件更短,您可能希望有 2 个文件:

  • Program.cs 和 Program 类,包含在 namespace Organization.Solution.Project

  • 带有 Emplyoee 结构的 Emplyoee.cs,包含在 namespace Organization.Solution.Project

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 2016-03-30
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多