我有一個有很多成員的父類。在構造它的子類時,如果可能的話,我想避免使用一堆輸入引數來參考基本建構式。
是否可以通過輸入其父類的物件來構造子類,并自動擁有由父類物件定義的所有父成員,而無需單獨參考基建構式或每個成員?
就像是:
class parent {
$name
$type
parent ($processName, $processType ) {
$this.Name = $processName
$this.Type = $processType
}
}
PS>$newParent = [parent]::new('FirstJob', 'report')
PS>$newParent.Name
FirstJob
class child : parent {
$order
child ( [parent]$process, $processOrder ) {
$this.type = $process.type
$this.order = $processOrder
}
}
PS>$newChild = [child]::new($newParent, 1)
PS>$newChild.Name
FirstJob
其中成員 Name 將通過父物件的輸入在子物件中自動定義。
這對我不起作用,因為子類似乎需要對基本建構式的參考。有可能避免這種情況嗎?對于 1 個成員,參考基類建構式(或重新定義子建構式中的父成員)看起來很簡單,但我有大約 8-10 個成員,并且希望將子類中的代碼集中在其構造上。
我所做的解決方法是使用單引數輸入多載父建構式,即以下內容:
class parent {
$name
$type
parent ($processName, $processType ) {
$this.processName = $processName
$this.processType = $processType
}
parent ( [parent]$parent ) {
$this.name = $parent.name
}
}
然后我在父類中使用新的基本建構式構造子類:
class child : parent {
$order
child ( [parent]$process, $processOrder ) : base ($process) {
$this.type = $process.type
$this.order = $processOrder
}
}
PS>$newChild = [child]::new($newParent, 1)
PS>$newChild.Name
FirstJob
這可以正常作業,但如果我不必在新的父建構式中列出成員映射,那就太好了。如果可以的話,我想最小化父類定義中的代碼,只是為了保持最小化和更容易閱讀。
PowerShell 中是否有任何型別的來自父類的自動成員繼承?
在上面的父基建構式中,我什至交叉手指嘗試$this.* = $process了??當然不行。
uj5u.com熱心網友回復:
您可以使用反射列舉復制建構式中基類宣告的所有屬性:
class Parent
{
[string]$Name
[string]$Type
Parent([string]$ProcessName, [string]$ProcessType){
$this.Name = $ProcessName
$this.Type = $ProcessType
}
# define copy-constructor that blindly copies all property values from reference object to itself
Parent([Parent]$referenceObject) {
foreach($Property in [Parent].GetProperties()){
$Property.SetValue($this, $referenceObject.$($Property.Name))
}
}
}
在這里,[Parent].GetProperties()將回傳屬于[Parent](例如[string]$Name和[string]$Type)的每個屬性的元資料,并允許我們從參考物件中復制這兩個屬性的值。
現在,您只需在構造子實體時將父實體傳遞給復制建構式并完成它:
class Child : Parent
{
$Order
Child([Parent]$ParentProcess, $ProcessOrder) : base($ParentProcess)
{
$this.Order = $ProcessOrder
}
}
class AnotherChild : Parent
{
$SomethingElse
AnotherChild([Parent]$ParentProcess, $ProcessInfo) : base($ParentProcess)
{
$this.SomethingElse = $ProcessInfo
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/420899.html
標籤:
