【发布时间】:2012-02-27 01:35:55
【问题描述】:
我已经在 SO 和其他网站上搜索过这个问题,但我还没有找到(或找到)我的案例的解决方案。
我有一个名为EnteBase 的抽象类,我将它用作其他两个类Regione 和Provincia 的基础(duh!)。
EnteBase:
public abstract class EnteBase
{
public EnteBase ()
: this( "Sconosciuto", 0 )
{
}
public EnteBase ( string nome )
: this( nome, 0 )
{
}
public EnteBase ( string nome, int numeroComuni )
{
this.Nome = nome;
this.NumeroComuni = numeroComuni;
}
private string nome;
public string Nome
{
[...]
}
private int numeroComuni;
public int NumeroComuni
{
[...]
}
}
Regione:
public class Regione : EnteBase
{
public List<Provincia> Province
{
[...]
}
public Regione ()
: base()
{
this.Province = new List<Provincia>();
}
public Regione ( string nome )
: this()
{
}
public Regione ( string nome, int numeroComuni )
: this()
{
}
public void AggiungiProvincia ( Provincia provincia )
{
Province.Add( provincia );
}
}
Provincia:
public class Provincia : EnteBase
{
private string sigla;
public string Sigla
{
[...]
}
public Provincia ()
: base()
{
}
public Provincia ( string nome )
: this()
{
this.Nome = nome;
}
public Provincia ( string nome, int numeroComuni )
: this()
{
this.Nome = nome;
this.NumeroComuni = numeroComuni;
}
public Provincia( string nome, int numeroComuni, string sigla)
: this()
{
this.Nome = nome;
this.NumeroComuni = numeroComuni;
this.Sigla = sigla;
}
}
我的问题如下:
- 在基类的所有构造函数中使用
:this()是否正确,除了具有最多参数的构造函数,其他指向后者? - 使用
:this()指向Provincia和Regione类中的基本构造函数,然后从方法本身内部分配给字段是否正确?
我的问题源于我想在每种方法中同时使用:this() 和:base()。当我发现这不可能时,我寻找解决方案,但我找不到一种方法来应用我在 this question 和 this one 中看到的内容。
P.S.:在构造函数中,是首选使用this.FieldName还是只使用FieldName?
【问题讨论】:
-
我想你忘了将字段初始化复制到
Regione构造函数中。 -
@hvd 谢谢,我不小心漏掉了
标签: c# constructor this grouping base