4

我有一个基类和一个子类。基类包含一些变量,子类包含一些变量。

我需要做的是,当我创建子类的对象时,我在其构造函数中传递基类对象,它将设置子对象的基类变量。

代码:

public class BaseClass
{
    public int BaseInteger;
    public double BaseDouble;
    public bool BaseBool;
}

public class ChildClass : BaseClass
{
    public ChildClass(BaseClass baseClass)
    {
        this.base = baseClass;     // I am trying to do this.
    }

    public int ChildInteger;
    public string ChildString;
}

那么我在这里尝试做的事情有可能吗?如何?当我尝试这段代码时,我得到了这个错误。

Use of keyword 'base' is not valid in this context
4

3 回答 3

5

You have to realize that ChildClass does not contain BaseClass but rather inherits from it.

That is why you can access data and methods that were defined in the base class using the this keyword (this.BaseInteger for example).

And that is also why you cannot 'set' the BaseClass of your ChildClass, it doesn't contain one.

Nevertheless, there are some useful patterns to achieve what you're trying to do, for example:

public class BaseClass
{
    protected BaseClass() {}

    protected BaseClass(BaseClass initData)
    {
        this.BaseInteger = initData.BaseInteger;
        this.BaseDouble = initData.BaseDouble;
        this.BaseBool = initData.BaseBool;
    }

    public int BaseInteger;
    public double BaseDouble;
    public bool BaseBool;
}

public class ChildClass : BaseClass
{
    public ChildClass() {}

    public ChildClass(BaseClass baseClass) : base(baseClass)
    {
    }

    public int ChildInteger;
    public string ChildString;
}

Thanks to @svick for his suggestions.

于 2013-06-20T08:00:11.300 回答
1

I think the most elegant way is to create a second constructor in the BaseClass class that takes a BaseClass instance from which it should initialize its fields. Then you can simply call this base constructor in your ChildClass class:

public class BaseClass
{
    public int BaseInteger;
    public double BaseDouble;
    public bool BaseBool;

    public BaseClass()
    {
    }

    public BaseClass(BaseClass baseClass)
    {
        this.BaseInteger = baseClass.BaseInteger;
        this.BaseDouble = baseClass.BaseDouble;
        this.BaseBool = baseClass.BaseBool;
    }
}

public class ChildClass : BaseClass
{
    public int ChildInteger;
    public string ChildString;

    public ChildClass(BaseClass baseClass) : base(baseClass)
    {
    }

}

于 2013-06-20T08:00:58.207 回答
1
public class BaseClass
{
    public int BaseInteger;
    public double BaseDouble;
    public bool BaseBool;
}

public class ChildClass : BaseClass
{
    public ChildClass(BaseClass baseClass)
    {
        this.BaseInteger = baseClass.BaseInteger;
        this.BaseDouble = baseClass.BaseDouble;
        this.BaseBool = baseClass.BaseBool;
    }

    public int ChildInteger;
    public string ChildString;
}
于 2013-06-20T07:56:11.377 回答