PowerShell IComparable with subclasses

烈酒焚心 提交于 2019-12-01 22:31:55

The behavior is indeed surprising and I see that you've opened a GitHub issue to discuss it.

A few additional thoughts:

  • PowerShell's operators often have extended semantics and generally shouldn't be assumed to work the same as their C# counterparts in all cases - however, in this particular case they clearly should (see below).

  • The fact that -lt actually works with the base-class instances already points to a difference: the equivalent C# class would additionally require explicit overloading of the < and > operators in order to support to support use of <.

  • Interface implementations are inherited by derived classes in both PowerShell and C#, so there should be no need to cast to the base class in order to apply -lt.


What seems to be happening here is that PowerShell blindly tries to convert the RHS to the type of the LHS without considering their shared base class.

The problem does not arise if the RHS type directly derives from the LHS type (but not the other way around); e.g.:

$base1 -lt $subA1  # OK: SubClassA (RHS) derives from BaseClass (LHS) 

$subA1 -lt $base1  # !! BREAKS: BaseClass (RHS) does NOT derive from SubClassA (LHS)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!