你所拥有的有什么问题?这在 PowerShell 5.0 中运行良好:
Class ControllerError : System.Exception
{
}
Class OperationFailed : ControllerError
{
$Code
$Message
OperationFailed ($Code, $Message)
{
$this.Code = $Code
$this.Message = $Message
}
}
$o = [operationfailed]::new("500","Internal server errror")
$o.Code
500
$o.Message
Internal server errror
$o | Get-Member | Select Name, MemberType
Name MemberType
---- ----------
Equals Method
GetBaseException Method
GetHashCode Method
GetObjectData Method
GetType Method
ToString Method
Code Property
Data Property
HelpLink Property
HResult Property
InnerException Property
Message Property
Source Property
StackTrace Property
TargetSite Property
$o.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False OperationFailed ControllerError
$o.gettype().BaseType
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False ControllerError System.Exception
我建议为 and 指定一个类型$Code
,$Message
因为您可能不希望它们是System.Object
. 前任。:
Class OperationFailed : ControllerError
{
[string]$Code
[string]$Message
OperationFailed ([string]$Code, [string]$Message)
{
$this.Code = $Code
$this.Message = $Message
}
}
如果你真的想使用基本构造函数(或者你想使用 Powershell < 5.0),那么你需要使用 C# 和Add-Type
$def = @"
public class ControllerError : System.Exception
{
public ControllerError(string message) : base(message) { }
}
public class OperationFailed : ControllerError
{
public string Code;
public OperationFailed(string code, string message) : base(message)
{
this.Code = code;
}
}
"@
Add-Type -TypeDefinition $def
$o = [OperationFailed]::new("500","internal server error")