我目前正在嘗試構造一個從不同對象派生的對象,但在調用基礎構造函數之前,我想進行一些參數驗證。在構造函數中使用base()
public FuelMotorCycle(string owner) : base(owner)
{
argumentValidation(owner);
}
現在我明白了最初的基礎構造首先被調用,有沒有辦法只有argumentValidation方法後,我可以打電話了嗎?
我目前正在嘗試構造一個從不同對象派生的對象,但在調用基礎構造函數之前,我想進行一些參數驗證。在構造函數中使用base()
public FuelMotorCycle(string owner) : base(owner)
{
argumentValidation(owner);
}
現在我明白了最初的基礎構造首先被調用,有沒有辦法只有argumentValidation方法後,我可以打電話了嗎?
現在我明白了,最初基礎構造函數首先被調用, 是否有一種方法,我可以在argumentValidation方法之後調用它?
不,至少不是很直接。
但是你可以用小解決方法,你必須static
方法,它的參數,驗證它,如果它是有效的還是拋出一個異常,如果它不是返回它:
private static string argumentValidate(string owner)
{
if (/* validation logic for owner */) return owner;
else throw new YourInvalidArgumentException();
}
然後纔有派生類的構造函數通過這種方法傳遞參數給他們的base
構造函數之前:
public FuelMotorCycle(string owner) : base(argumentValidate(owner))
{
}
首先調用基類構造函數,然後執行方法體中的所有內容。
基礎構造函數將首先被調用。
此示例:
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");
}
}
將輸出:
base
derived
基地在構造中使用。派生類構造函數需要從其基類調用構造函數。當缺省構造函數不存在時,自定義基類構造函數可以與base一起被引用。 基類的構造函數被調用之前派生類的構造函數,但是派生類初始化得到基類initializers.I之前調用也建議你看contructor execution from msdn
using System;
public class A // This is the base class.
{
public A(int value)
{
// Executes some code in the constructor.
Console.WriteLine("Base constructor A()");
}
}
public class B : A // This class derives from the previous class.
{
public B(int value)
: base(value)
{
// The base constructor is called first.
// ... Then this code is executed.
Console.WriteLine("Derived constructor B()");
}
}
class Program
{
static void Main()
{
// Create a new instance of class A, which is the base class.
// ... Then create an instance of B, which executes the base constructor.
A a = new A(0);
B b = new B(1);
}
}
這裏是輸出:
Base constructor A()
Base constructor A()
Derived constructor B()
根據驗證方法是什麼,你可能能夠d類似於:
public FuelMotorCycle(string owner)
: base(argumentValidationReturningValidatedArg(owner))
{
}
如果驗證函數是一個靜態方法,例如,這應該沒問題。
「基地」建設將首先發生。 –
你總是可以按F5鍵來看看自己。 –
重複:[C#構造函數執行順序](http://stackoverflow.com/a/1882778/1945631) –