将此传递给基本构造函数 [英] Pass this to base constructor
本文介绍了将此传递给基本构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为正在编写的程序实现良好的设计模式.我有一个这样的类结构.
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))
{
}
}
现在,我确定您知道,您不能在基本构造函数中传递此参数,因为该对象此时尚未初始化.无论如何,我真的希望有一个解决方法.允许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屋!
查看全文