C# virtual (or abstract) static methods

前端 未结 4 1953
孤独总比滥情好
孤独总比滥情好 2020-12-06 05:45

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

class Program {
    static vo         


        
4条回答
  •  醉酒成梦
    2020-12-06 06:36

    You could store the TargetMethod as a delegate, which a subclass could change as needed:

    class TestBase {
        protected static Action _targetMethod;
    
        static new() {
           _targetMethod = new Action(() => {
               Console.WriteLine("Base class");
           });
        }
    
        public static void TargetMethod() {
            _targetMethod();
        }
    
        public static void Operation() {
            TargetMethod();
        }
    }
    
    class TestChild : TestBase {
        static new() {
           _targetMethod = new Action(() => {
               Console.WriteLine("Child class");
           });
        }
    }
    

    Since these are static instances, though - the _targetMethod is shared across all instances - changing it in TestChild changes it for TestBase as well. You may or may not care about that. If you do, generics or a Dictionary might help.

    Overall, though, you'd have a much easier time if you didn't insist on statics, or perhaps used composition instead of inheritance.

提交回复
热议问题