类base()构造函数并传递给它

时间:2014-09-18 17:34:31

标签: c# constructor derived-class base-class

我正在尝试为我正在编写的程序实现良好的设计模式。我有这样的课程结构。

abstract class SomeBase
{
     public SomeObject obj { get; protected set; } 

     protected SomeBase(SomeObject x)
     {
           obj = x;
     }

     //Other methods and fields...
}

public class SomeDerived : SomeBase
{

     public SomeDerived() : base(new SomeObject(this))
     {

     }

}

现在,我确定你现在,你不能在一个构造函数中传递它,因为该对象没有被初始化。但我真的希望有一个解决方法。允许SomeDerived()处理基类字段的设置对我来说不是最佳做法。我想将这个新对象传递给链。

有什么想法吗?

3 个答案:

答案 0 :(得分:4)

这是不可能的,在构造函数之后使用Init方法:

 abstract class SomeBase
 {
      private SomeObject _obj { get; set; } 
      public SomeObject obj 
      {
           get 
           {    // check _obj is inited:
                if (_obj == null) throw new <exception of your choice> ;
                return _obj;
           } 
      }

      protected SomeBase()
      {
           obj = null;
      }

      protected void Init()
      {
           obj = x;
      }

      //Other methods and fields...
 }

 public class SomeDerived : SomeBase
 {

      public SomeDerived() : base()
      {
           Init(new SomeObject(this));
      }

 }

答案 1 :(得分:0)

好吧,实际上您已经在基本构造函数中拥有它,因此不需要传递它。

abstract class SomeBase
{
    public SomeObject obj { get; protected set; }

    protected SomeBase()
    {
        obj = (SomeObject)Activator.CreateInstance(typeof(SomeObject), this); // "this" here is SomeDerived object
    }
}

class SomeDerived : SomeBase
{
    public SomeDerived()
    {
    }
}

class SomeObject
{
    public SomeObject(SomeDerived obj)
    {
        if (obj.obj == null)
        {
            // You have the reference to SomeDerived here
            // But its properties are not yet initialized (both SomeDerived and SomeBase constructors are in the progress of execution)
            // So you should not access them in the SomeObject class constructor
        }
    }
}

答案 2 :(得分:-2)

1)构造函数完全是它设计的错误 - 它看起来像实例的方法,但实际上它是半实例的半方法。

2)&#34;具有模式的优秀设计程序&#34;如我们在这里看到的那样,不要在聚合中的类之间造成直接的循环依赖 - 这两个类必须在创建时知道并相互使用(!!!)谁知道SomeObject做什么&#34;这个&#34;在它的构造函数???

所以&#34;模式&#34; 2个问题在哪里 - 类之间的高依赖性和初始化逻辑的不可用的封装。所以我们必须找到&#34; pattern&#34;解决问题的方法......嗯......做什么......

在代码中你提供我看到派生类只是为属性obj提供了它自己的逻辑 你可以将它重写为自动初始化的属性

public abstract class MyClass{
     private SomeObject _obj ; 
     public SomeObject Obj {get { return  _obj ?? (_obj = InitializeObj() );}} //no setter needed
     protected abstract SomeObject InitializeObj();
}

public class MyRealClass:MyClass {
    protected override SomeObject InitializeObj(){
        return new VerySpecialSomeObject(this, other, another, 1, 2 , false, option: new Options());
    }   
}

对于您的示例,此类解决方案提供单一&#34;模式&#34;赢了 - &#34;多态性&#34; ))并获得额外的奖金 - 如果&#34; Obj&#34;将不会有用 - 它永远不会被创建))))

相关问题