将此传递给基础构造函数 [英] Pass this to base constructor

查看:32
本文介绍了将此传递给基础构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to implement good design patterns for a program I am writing. I have a class structure like this.

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))
     {

     }

}

现在我确定你知道,你不能在基本构造函数中传递 this,因为此时对象还没有被初始化.无论如何,我真的希望有一个解决方法.允许 SomeDerived() 处理基类字段的设置对我来说不是最佳实践.我想将这个新对象向上传递.

Now as I'm sure you know, you can't pass this in a base constructor, because the object hasn't been initialized at this point in time. Anyhow I was really hoping there was a workaround. It's not best practice for me to allow SomeDerived() to handle the setting of a base classes field. I would like to pass this new object up the chain.

推荐答案

这个不行,在构造函数后面用一个Init方法:

This is not possible, use an Init method after the constructor:

 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));
      }

 }

这篇关于将此传递给基础构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆