【问题标题】:'Employee' is a 'namespace' but is used like a 'type' [duplicate]“员工”是一个“命名空间”,但用作“类型”[重复]
【发布时间】:2016-02-09 14:43:23
【问题描述】:

'Employee' 是一个“命名空间”,但用作“类型”。我似乎无法纠正这 4 个错误。帮助任何人?第 12 行和第 27 行。我在 2 个错误行上做了解释。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Employee
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee firstEmployee = new Employee();   **(2 errors on line for Employee)**
            ApplicationUtilities.DisplayApplicationInformation(); //display the                     header for the application
            ApplicationUtilities.DisplayDivider("Start Program"); //Show heading that the program has started
            ApplicationUtilities.DisplayDivider("Prompt for employee information and create first employee"); //Heading that shows we are ready to input first employee information
            firstEmployee.firstName = InputUtilities.getStringInputValue("First Name"); //Get first name input from the user
            firstEmployee.lastName = InputUtilities.getStringInputValue("Last Name");//Get last name input from the user
            firstEmployee.gender = InputUtilities.getCharInputValue("Gender");//Get gender input from the user
            firstEmployee.dependents = InputUtilities.getIntegerInputValue("# Dependents");//Get dependent input from the user
            firstEmployee.annualSalary = InputUtilities.getDoubleInputValue("Annual Salary");//Get annual salary input from the user

            Console.WriteLine("");
            Console.Write(firstEmployee.ToString());

            ApplicationUtilities.PauseExecution();
            Employee secondEmployee = new Employee("First Name", "Last Name", 'F', 3, 52000); ////declare an instance of second employee object with overloaded constructor called     **(2 errors on this line for - Employee)**
            Console.Write(secondEmployee.ToString());
            ApplicationUtilities.TerminateApplication();
        }
    }
}

【问题讨论】:

  • 你有一个命名空间和一个同名的类 - Employee。这是不允许的。
  • @JamieMeyer 不正确。只需要使用完全限定名称(不推荐)
  • 感谢您的更正,米奇。今天学到了新东西。我确信有一个最佳实践建议不要这样做,以避免混淆编译器。

标签: c#


【解决方案1】:

正如错误所暗示的,命名空间和类共享相同的名称。编译器对您要实例化的具体内容感到困惑。

快速修复:在创建Employee 的新实例时指定命名空间,以便编译器知道您要在同名命名空间创建类的新实例。

Employee.Employee firstEmployee = new Employee.Employee();

正确修复:重命名命名空间,以便您可以更轻松地实例化类。

您可能还想从对编译器非常了解的人那里阅读这篇文章:Do not name a class the same as its namespace

FWIW,这种大小的小型应用在技术上需要命名空间。但是(正如 Neolisk 指出的那样)如果你确实使用了一个,那么use a good one。随着程序的增长,您可以将代表人的类(例如 Employee)分组到名为 Entity 的命名空间中。

【讨论】:

  • 别忘了提到Employee.Employee 是代码异味,与Employees.Employee 相同,并且通常Employee 不够广泛,不足以成为命名空间的良好候选者。说到好的命名空间示例,Entity 可能就是它了。
【解决方案2】:

重命名您的 Employee 命名空间或重命名您的 Employee 类。

【讨论】:

    猜你喜欢
    • 2015-07-22
    • 2021-03-31
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2013-02-07
    相关资源
    最近更新 更多