我们可以在PowerShell脚本中实现.NET接口吗?

问题描述:

可以说我们在用C#编写的.NET类库中定义了一些接口.有没有办法在PowerShell脚本中实现这些接口?

Lets say we have a few interfaces defined in a .NET class library written in C#. Is there a way to implement these interfaces in a PowerShell script?

将此称为业务需求.作为供应商,我们提供一些由客户实施以使用我们产品的接口.我们的一位客户希望通过PowerShell脚本执行此操作.

Call this a business need. We as a vendor, provide a few interfaces that are implemented by our customers to use our product. One of our customer wants to do this from PowerShell script.

下面是一个使用PowerShell 5.0实现.Net IEqualityComparer 接口的简单示例:

Here's a simple example with PowerShell 5.0 implementing the .Net IEqualityComparer interface:

Class A:System.Collections.IEqualityComparer {
  [bool]Equals($x,$y)  { return $x -eq $y        }
  [int]GetHashCode($x) { return $x.GetHashCode() }
}
[A]$a=[A]::new()
$a.Equals(1,1) -- returns True
$a.Equals(1,2) -- returns False
$a.GetHashCode("OK") -- returns 2041362128

您甚至可以拥有一个类(称为A),该类继承自另一个类(称为B)并实现IEqualityComparer:

You could even have a class (called A), which inherits from another class (called B) and implements IEqualityComparer:

Class A:B,System.Collections.IEqualityComparer {