派生类在自己的静态方法中调用基类的静态方法

Joh*_*man 5 c# static-methods derived-class

我已阅读了以下SO文章

所有这些似乎都非常接近我的问题,并且有很好的答案,但他们似乎没有回答我的问题,只是说我需要使方法非静态.

一个例子:

abstract public class baseClass
{
    private static List<string> attributeNames = new List(new string {"property1","property2"});
    // code for property definition and access
    virtual public static bool ValidAttribtue(string attributeName)
    {
        if (attributeNames.Contains(attributeName))
            return true;
        else
            return false;
    }
}
class derivedA : baseClass
{
    private static List<string> attributeNames = new List(new string {"property3","property4"});
    // code for property definition and access
    public static override bool ValidAttribute(string attributeName)
    {
        if (attributeNames.Contains(attributeName))
        {
            return true;
        }
        else
        {
            return base.ValidAttribute(attributeName);
        }
    }
}
class derivedB : baseClass
{
    private static List<string> attributeNames = new List(new string {"property10","property11"});
    // code for property definition and access
    public static override bool ValidAttribute(string attributeName)
    {
        if (attributeNames.Contains(attributeName))
        {
            return true;
        }
        else
        {
            return base.ValidAttribute(attributeName);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

derivedA将具有属性1,2,3,4而derivedB将具有属性1,2,10,11.属性列表似乎是特定于类的值,不能在任何时候更改.我认为它会是静态的.

我的设计是错误的,因为我不想使用静态方法吗?

上面的例子让我觉得需要继承静态方法,但似乎尝试这样做是一个设计缺陷.任何人都可以帮助我理解以这种方式编写或构造类的错误吗?

Jon*_*eet 8

我的设计是错误的,因为我不想使用静态方法吗?

是.除了其他任何东西,你试图将静态方法声明为virtual(然后覆盖它),这是不允许的.当你是base一个关键字时,你也试图声明一个叫做的类.

静态方法根本不是多态的.多态性的基础是所涉及的实例的执行时间类型可以与表达式的编译时类型不同,并且基于执行时间类型选择实现.这一概念是没有意义的静态方法,因为没有实例.

当然,你可以在派生类中创建一个静态方法,在基类中调用一个静态方法 - 但是在任何地方都不会有任何多态.

作为旁注,所有方法都可以用更易读的方式编写:

// Base class implementation
return attributeNames.Contains(attributeName);

// Derived class implementations
return attributeNames.Contains(attributeName) ||
       BaseClass.ValidAttribute(attributeName);
Run Code Online (Sandbox Code Playgroud)