Call Constructor Base after Code Execution

后端 未结 9 2001
攒了一身酷
攒了一身酷 2021-02-12 12:33

Let say we have Class A and Class B. ClassB extends Class A. (ClassB : ClassA)

Now let\'s say that whenever I instantiate ClassB, I\'d like to Run some Random code and o

9条回答
  •  隐瞒了意图╮
    2021-02-12 13:19

    I had the same problem. I found this solution to be the best if you don't have access to the base class.

    public class BaseClass
    {
        public BaseClass(string someValue)
        {
            Console.WriteLine(someValue);
        }
    }
    
    public class MyClass : BaseClass
    {
        private MyClass(string someValue)
            : base(someValue)
        {
        }
    
        public static MyClass GetNewInstance(string someValue, bool overrideValue = false)
        {
            if (overrideValue)
            {
                someValue = "42";
            }
            return new MyClass(someValue);
        }
    }
    

提交回复
热议问题