C# 从基类调用静态函数

C# 从基类调用静态函数,c#,static,static-methods,C#,Static,Static Methods,我有一个类employee,其中我有一个静态函数,其中包含count number employee和count to type employee(例如教师、助理教师、个人助理等)。为此,我在其中有一个静态类,其中包含一个static count For number of employee,在每个子类中,我希望访问基类静态方法 class Employee{ private static int emp; //...code static void IncreaseE

我有一个类employee,其中我有一个静态函数,其中包含count number employee和count to type employee(例如教师、助理教师、个人助理等)。为此,我在其中有一个静态类,其中包含一个static count For number of employee,在每个子类中,我希望访问基类静态方法

class Employee{
    private static int emp;
    //...code

    static void IncreaseEmployeeCount()
    {
        emp=emp+1;
    }

}

class Teacher : Employee{
    private static int tchr;

    //...code

    static void IncreaseTeacherCount()
    {
        tchr = tchr + 1;
    }
}
如何使用子类访问基类静态方法。它尝试使用以下命令,但由于编译时错误而失败:

Teacher teacher = new Teacher();
teacher.IncreaseEmployeeCount();
“Employee.IncreaseEmployeeCount()”由于其保护级别而无法访问

添加
public
访问级别仍会出现错误:

无法使用实例引用访问成员“Employee.IncreaseEmployeeCount()”;改为使用类型名称限定它


作为静态方法,您不能通过类的实例访问它。你是这样做的

Teacher.IncreaseEmployeeCount();
注意:原始样本有其他编译错误:

  • 基类的方法需要声明为
    public
  • 将返回值与方法体对齐,因为它声明为
    int
    ,应该是
    void
    或have
    return{something}

应该是
Employee.IncreaseEmployeeCount()
Teacher.IncreaseTeacherCount()
。请记住,这些是静态方法,因此它们不绑定到实例。您只需通过
ClassName.StaticMethod()

调用它们,为什么要在这个问题中添加
c++
标记?您应该尝试super.employeeCount()而不是tch。tch是一个实例,而不是它本身的类。employeeCount()是类级别的函数,而不是实例级别的函数。@AlexeiLevenkov:除了从每个静态函数返回一个值外,代码是可接受的C#。@PaulF我被所有小写字母搞糊涂了。。。事实上,我已经更新了示例以匹配默认的C#准则,并且更易于编译,这应该是一个更好的问题(我也不能再关闭这个问题了),但这不会起作用。静态方法不是由子类继承的,它们特定于/绑定到类,而不是实例。因此,我们必须像在c中调用
employee.employeeCount()
那样调用它,因为它们是继承的-试试看。您可能会得到一个Resharper警告“通过派生类型访问类型的静态成员”,但这是一个警告,而不是编译器错误。您是对的,它确实有效,我会告诉您。但是,此行为只是编译器提供的快捷方式。语法糖
teacher.employeeCount()
将编译为
employee.employeeCount()
。正如我所说,
teacher
没有静态成员
employeeCount()
,因为静态成员不是继承的。通常我不同意最佳做法-但是Win Forms控件使用继承的静态属性和方法&从派生类而不是基控件类调用它们似乎很自然。