Extending accelerated .Net class using the original constructors

為{幸葍}努か 提交于 2021-02-08 09:32:06

问题


Inspired by theses questions:

  • Get a specific octet from the string representation of an IPv4 address
  • Powershell - Checking IP Address range based on CSV file

I am trying to extend the IPAddress class with an ToBigInt() method in PowerShell (if even possible) to be able to easily compare (IPv4 and IPv6) addresses using comparison operations along with -lt and -gt. E.g.:

([IPAddress]'2001:db8::8a2e:370:7334').ToBigInt() -lt ([IPAddress]'2001:db8::8a2e:370:7335').ToBigInt()

My first attempt:

class IPAddress : System.Net.IPAddress {
    [Void]ToBigInt() {
        $BigInt = [BigInt]0
        foreach ($Byte in $This.GetAddressBytes()) {
            $BigInt = ($BigInt -shl 8) + $Byte
        }
        $BigInt
    }
}

Causes an error:

Line |
   1 |  class IPAddress : System.Net.IPAddress {
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Base class 'IPAddress' does not contain a parameterless constructor.

So apparently, I need to add the ([IPAddress]::new) constructors to the sub class:

class IPAddress : System.Net.IPAddress {
    IPAddress ([long]$NewAddress) : base($NewAddress) { }
    IPAddress ([byte[]]$Address, [long]$ScopeId) : base($Address, $ScopeID) { }
    IPAddress ([System.ReadOnlySpan[byte]]$Address, [long]$ScopeId) : base($Address, $ScopeID) { }
    IPAddress ([byte[]]$Address) : base($Address) { }
    IPAddress ([System.ReadOnlySpan[byte]]$Address) : base($Address) { }
    
    [Void]ToBigInt() {
        $BigInt = [BigInt]0
        foreach ($Byte in $This.GetAddressBytes()) {
            $BigInt = ($BigInt -shl 8) + $Byte
        }
        $BigInt
    }
}

Now, the class defintion is accepted but when I try to create an IPAddress, like:

[IPAddress]'172.13.23.34'

I get a new error:

OperationStopped: Unable to cast object of type 'System.Net.IPAddress' to type 'IPAddress'.

How can I resolve this casting error?

来源:https://stackoverflow.com/questions/63765349/extending-accelerated-net-class-using-the-original-constructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!