本文介绍了C#虚拟(或抽象)的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静态继承工作就像实例继承。但你不能做静态方法虚拟的或抽象的。

Static inheritance works just like instance inheritance. Except you are not allowed to make static methods virtual or abstract.

class Program {
    static void Main(string[] args) {
        TestBase.TargetMethod();
        TestChild.TargetMethod();
        TestBase.Operation();
        TestChild.Operation();
    }
}

class TestBase {
    public static void TargetMethod() {
        Console.WriteLine("Base class");
    }

    public static void Operation() {
        TargetMethod();
    }
}

class TestChild : TestBase {
    public static new void TargetMethod() {
        Console.WriteLine("Child class");
    }
}

这将输出:

Base class
Child class
Base class
Base class

不过,我想:

Base class
Child class
Base class
Child class

如果它,我可以在静态方法,我会做虚拟TargetMethod,它会做的工作。但有一个变通来获得同样的效果?

If it I could on static methods, I would make TargetMethod virtual and it would do the job. But is there a work around to get the same effect?

编辑:是的,我可以把操作的一个副本在子类中,但这需要复制和粘贴code大位到每一个孩子,这在我的情况是约35个教学班,维护的噩梦

Yes, I could put a copy of Operation in the child class, but this would require copy and pasting a large bit of code into every child, which in my case is about 35 classes, a maintenance nightmare.

推荐答案

没有,你不能覆盖静态方法。 静态也意味着它是编译器静态地结合,所以在运行时没有发现被称为实际的方法,但在编译时结合

No, you cannot override a static method. "static" also means that it is statically bound by the compiler, so the actual method to be called is not found at runtime, but bound at compile time.

你应该做的是使类非静态。使该方法虚拟和覆盖它,使真正的继承充分受益。然后,如果你真的需要它,使静态入口点类的引用。例如一个静态的工厂,辛格尔顿(它是一个反模式在大多数情况下,但不如静态类),或者只是一个静态属性。

What you should do is make the class non-static. Make the method virtual and override it and make full benefit of real inheritance. Then, if you really need it, make a static entry point to a reference of your class. For instance a static factory, singleton (it's an anti-pattern in most of the cases but is as good as a static class) or just a static property.

这篇关于C#虚拟(或抽象)的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:02