基类构造函数会自动调用吗? [英] Will the base class constructor be automatically called?

查看:186
本文介绍了基类构造函数会自动调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Person 
{
public int age;
public Person()
{
age = 1;
}
}

类客户:人
{
public Customer()
{
age + = 1;
}
}

客户customer = new Customer();

客户的年龄是2吗?似乎基类的构造函数将被调用无论什么。如果是,为什么我们需要在结尾时调用 base

  public Customer():base()
{
.............
}
pre>

解决方案

这就是C#是怎么工作的。类型层次结构中每个类型的构造函数将按照Most Base - > Most Derived的顺序调用。



因此在您的特定实例中,它调用 Person(),然后 Customer )。您需要有时使用 base 构造函数的原因是当前类型下面的构造函数需要额外的参数。例如:

  public class Base 
{
public int SomeNumber {get;组; }

public Base(int someNumber)
{
SomeNumber = someNumber;
}
}

public class AlwaysThreeDerived:Base
{
public AlwaysThreeDerived()
:base(3)
{
}
}

为了构造 AlwaysThreeDerived 对象,它有一个无参数的构造函数。但是, Base 类型不会。所以为了创建一个无参数的构造函数,你需要提供一个参数给基本的构造函数,你可以用 base 实现。


class Person
{
    public int age;
    public Person()
    {
        age = 1;
    }
}

class Customer : Person
{
    public Customer()
    {
        age += 1;
    }
}

Customer customer = new Customer();

Would the age of customer be 2? It seems like the base class's constructor will be called no matter what. If so, why do we need to call base at the end sometimes?

public Customer() : base()
{
    .............
}

解决方案

This is simply how C# is going to work. The constructors for each type in the type hierarchy will be called in the order of Most Base -> Most Derived.

So in your particular instance, it calls Person(), and then Customer() in the constructor orders. The reason why you need to sometimes use the base constructor is when the constructors below the current type need additional parameters. For example:

public class Base
{
     public int SomeNumber { get; set; }

     public Base(int someNumber)
     {
         SomeNumber = someNumber;
     }
}

public class AlwaysThreeDerived : Base
{
    public AlwaysThreeDerived()
       : base(3)
    {
    }
}

In order to construct an AlwaysThreeDerived object, it has a parameterless constructor. However, the Base type does not. So in order to create a parametersless constructor, you need to provide an argument to the base constuctor, which you can do with the base implementation.

这篇关于基类构造函数会自动调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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