How to do constructor chaining in C#

前端 未结 8 1630
挽巷
挽巷 2020-11-22 16:25

I know that this is supposedly a super simple question, but I\'ve been struggling with the concept for some time now.

My question is, how do you chain constructors

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 17:02

    There's another important point in constructor chaining: order. Why? Let's say that you have an object being constructed at runtime by a framework that expects it's default constructor. If you want to be able to pass in values while still having the ability to pass in constructor argments when you want, this is extremely useful.

    I could for instance have a backing variable that gets set to a default value by my default constructor but has the ability to be overwritten.

    public class MyClass
    {
      private IDependency _myDependency;
      MyClass(){ _myDependency = new DefaultDependency(); }
      MYClass(IMyDependency dependency) : this() {
        _myDependency = dependency; //now our dependency object replaces the defaultDependency
      }
    }
    

提交回复
热议问题