在C#中,我们需要调用基本构造函数吗?
时间:2020-03-05 18:41:08 来源:igfitidea点击:
在C#中,如果我有一个带有默认构造函数的继承类,是否必须显式调用基类的构造函数,还是将其隐式调用?
class BaseClass { public BaseClass() { // ... some code } } class MyClass : BaseClass { public MyClass() // Do I need to put ": base()" here or is it implied? { // ... some code } }
解决方案
回答
AFAIK,仅在需要将任何值传递给它时,才需要调用基本构造函数。
回答
这是隐含的。
回答
我们不需要显式调用基本构造函数,它将被隐式调用。
稍微扩展一下示例并创建一个控制台应用程序,我们可以亲自验证此行为:
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { MyClass foo = new MyClass(); Console.ReadLine(); } } class BaseClass { public BaseClass() { Console.WriteLine("BaseClass constructor called."); } } class MyClass : BaseClass { public MyClass() { Console.WriteLine("MyClass constructor called."); } } }
回答
派生类建立在基类的基础上。如果考虑一下,则必须先在内存中实例化基础对象,然后才能将派生类添加到该对象。因此,将在创建派生对象的过程中创建基础对象。因此,不,我们不调用构造函数。
回答
如果没有参数,则暗示它。这是因为我们需要实现采用值的构造函数,请参见下面的代码作为示例:
public class SuperClassEmptyCtor { public SuperClassEmptyCtor() { // Default Ctor } } public class SubClassA : SuperClassEmptyCtor { // No Ctor's this is fine since we have // a default (empty ctor in the base) } public class SuperClassCtor { public SuperClassCtor(string value) { // Default Ctor } } public class SubClassB : SuperClassCtor { // This fails because we need to satisfy // the ctor for the base class. } public class SubClassC : SuperClassCtor { public SubClassC(string value) : base(value) { // make it easy and pipe the params // straight to the base! } }
回答
对于基本的无参数构造函数而言,它是隐含的,但对于当前类中的默认值,它是必需的:
public class BaseClass { protected string X; public BaseClass() { this.X = "Foo"; } } public class MyClass : BaseClass { public MyClass() // no ref to base needed { // initialise stuff this.X = "bar"; } public MyClass(int param1, string param2) :this() // This is needed to hit the parameterless ..ctor { // this.X will be "bar" } public MyClass(string param1, int param2) // :base() // can be implied { // this.X will be "foo" } }
回答
我们不需要显式调用基本构造函数,它会被隐式调用,但是有时我们需要将参数传递给构造函数,在这种情况下,我们可以执行以下操作:
using System; namespace StackOverflow.Examples { class Program { static void Main(string[] args) { NewClass foo = new NewClass("parameter1","parameter2"); Console.WriteLine(foo.GetUpperParameter()); Console.ReadKey(); } } interface IClass { string GetUpperParameter(); } class BaseClass : IClass { private string parameter; public BaseClass (string someParameter) { this.parameter = someParameter; } public string GetUpperParameter() { return this.parameter.ToUpper(); } } class NewClass : IClass { private BaseClass internalClass; private string newParameter; public NewClass (string someParameter, string newParameter) { this.internalClass = new BaseClass(someParameter); this.newParameter = newParameter; } public string GetUpperParameter() { return this.internalClass.GetUpperParameter() + this.newParameter.ToUpper(); } } }
注意:如果有人知道更好的解决方案,请告诉我。