0

python的豪华等价物是什么:

class ControllerError(Exception):


class OperationFailed(ControllerError):

  def __init__(self, code = None, message = None):
    super(ControllerError, self).__init__(message)
    self.code = code
    self.message = message

对于 SO 纯粹主义者,我迄今为止的尝试:

Class ControllerError : System.Exception
{

}


Class OperationFailed : ControllerError
{
    $Code
    $Message

    OperationFailed ($Code, $Message)
    {
        $this.Code = $Code
        $this.Message = $Message
    }
}
4

1 回答 1

1

你所拥有的有什么问题?这在 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")
于 2016-04-27T21:19:01.290 回答