关于c#:从基类调用静态函数

Calling static function from base class

我有一个类雇员,其中我有一个静态函数,其中包括count number employee和count to type of employee(如teacher、assistant teacher、personal assistant等)。为此,我在内部有一个静态类,其中我有一个静态的雇员数计数,在每个子类中,我想访问基类静态方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
    }
}

如何使用子类访问基类静态方法。它尝试使用以下方法,但由于编译时错误而失败:

1
2
Teacher teacher = new Teacher();
teacher.IncreaseEmployeeCount();

'Employee.IncreaseEmployeeCount()' is inaccessible due to its protection level

添加public访问级别仍会产生错误:

Member 'Employee.IncreaseEmployeeCount()' cannot be accessed with an instance reference; qualify it with a type name instead


应该是Employee.IncreaseEmployeeCount()Teacher.IncreaseTeacherCount()。记住,这些是静态方法,因此它们不绑定到实例。你只要通过ClassName.StaticMethod()给他们打电话


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

1
Teacher.IncreaseEmployeeCount();

Notes原始样本有其他编译错误:

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