inheritance in c#
what is the difference between
class abc : qwe
{
}
and
class zxc : qwe
{
zxc() : base(new someAnoth开发者_JAVA百科erclass()).
{
}
}
The difference is, that in your first code snippet you're calling the parameterless base class constructor, whereas in your second code snippet you're calling the base class constructor with a parameter.
Your base class might be defined as follows:
class qwe{
public qwe(){ /* Some code */ }
public qwe(SomeAnotherclass ac){ /* Some other code */ }
}
The default constructor for your abc
class looks exactly like the following:
class abc{
public abc() : base() {}
}
When it comes to inheritance, both are the same: zxc is_a qwe
In your second example you simply define the empty zxc constructor to call the qwe constructor before with an argument you generate (someAnotherclass()). That usually means an aggregation if you keep the reference somewhere, not inheritance.
The result will be the same.
By calling the constructor on zxc you can add some functionality AND call the base constructor.
In the second code snippet, you are chaining the default (no parameter) constructor of the inherited to a constructor of the base class that takes a someAnotherClass
parameter.
When initializing the zxc class, this will call the qwe constructor with the new someAnotherClass
.
With the first code snippet, none of this constructor chaining is happening.
The first is a class which base is qwe
. The second is the same but it also have constructor that executes specified constructor (with diffrent arguments then default one) from base class while being invoked.
Second snippet shows how to handle the situation when base class do not have default constructor. The reason of that requirement is that derived class constructor is always calling base class constructor first. If base constructor needs some parameters then you have to call it explicetely.
Probably you mean
class abc : qwe
{
}
and
class zxc : qwe
{
public zxc() : base(new someAnotherClass()).
{
}
}
This mean that
class qwe
{
// public constructor accepting SomeAnotherType
public qwe(SomeAnotherType someAnotherClass)
{
}
}
Such approach is called nested constructor call
or constructor chaining
精彩评论