Calling the base constructor in C#

前端 未结 12 2594
南笙
南笙 2020-11-22 03:04

If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?

For exa

12条回答
  •  情话喂你
    2020-11-22 03:15

    If you need to call the base constructor but not right away because your new (derived) class needs to do some data manipulation, the best solution is to resort to factory method. What you need to do is to mark private your derived constructor, then make a static method in your class that will do all the necessary stuff and later call the constructor and return the object.

    public class MyClass : BaseClass
    {
        private MyClass(string someString) : base(someString)
        {
            //your code goes in here
        }
    
        public static MyClass FactoryMethod(string someString)
        {
            //whatever you want to do with your string before passing it in
            return new MyClass(someString);
        }
    }
    

提交回复
热议问题