在构造函数中使用:base()

Ste*_*eld 2 c# inheritance

我目前正在尝试构造一个派生自不同对象的对象,但在调用基础构造函数之前,我想进行一些参数验证.

public FuelMotorCycle(string owner) : base(owner)
{
    argumentValidation(owner);
}
Run Code Online (Sandbox Code Playgroud)

现在我明白了最初首先调用基础构造函数,有没有办法只能在argumentValidation方法之后调用它?

Tho*_*sen 5

首先调用基础构造函数.

这个例子:

class Program
{
    static void Main(string[] args)
    {
        var dc = new DerivedClass();
        System.Console.Read();
    }
}

class BaseClass
{
    public BaseClass(){
        System.Console.WriteLine("base");
    }
}

class DerivedClass : BaseClass
{
    public DerivedClass()
        : base()
    {
        System.Console.WriteLine("derived");
    }
}
Run Code Online (Sandbox Code Playgroud)

将输出:

base
derived
Run Code Online (Sandbox Code Playgroud)


The*_*kis 5

现在我明白了,最初首先调用基本构造函数,有没有办法只能在 argumentValidation 方法之后调用它?

不,至少不是很直接。

但是您可以使用一个小的解决方法,您可以使用static接受参数的方法,对其进行验证并在有效时返回它,或者在无效时抛出异常:

private static string argumentValidate(string owner)
{
    if (/* validation logic for owner */) return owner;
    else throw new YourInvalidArgumentException();
}
Run Code Online (Sandbox Code Playgroud)

然后让派生类构造函数通过此方法传递参数,然后再将它们传递给base构造函数:

public FuelMotorCycle(string owner) : base(argumentValidate(owner))
{
}
Run Code Online (Sandbox Code Playgroud)