Call Constructor Base after Code Execution

后端 未结 9 2012
攒了一身酷
攒了一身酷 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:38

    Actually, you can:

    class Foo
    {
        public Foo(string s)
        {
            Console.WriteLine("inside foo");
            Console.WriteLine("foo" + s);
        }
    }
    
    class Bar : Foo
    {
        public Bar(string s) : base(((Func)(delegate ()
        {
            Console.WriteLine("before foo");
            return "bar" + s;
        }))())
        {
            Console.WriteLine("inside bar");
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            new Bar("baz");
        }
    }
    

    Output:

    before foo
    inside foo
    foobarbaz
    inside bar
    

    But I will prefer to not use this trick if it is possible.

提交回复
热议问题