C# virtual (or abstract) static methods

前端 未结 4 1947
孤独总比滥情好
孤独总比滥情好 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:29

    If you are looking to do abstract static methods, then this works, and turns out to be the easiest solution for me to adapt to:

    class TestBase where ChildType : TestBase {
        //public static abstract void TargetMethod();
    
        public static void Operation() {
            typeof(ChildType).GetMethod("TargetMethod").Invoke(null, null);
        }
    }
    
    class TestChild : TestBase {
        public static void TargetMethod() {
            Console.WriteLine("Child class");
        }
    }
    

    But I am still marking Stafan as the solution because using instance inheritance is probably the best recommendation for anyone in a similar situation. But I simply would have to rewrite too much code for it.

提交回复
热议问题