Powershell 5 类和单例

标签 powershell

是否有使用 PowerShell 5.0 中的类构造创建单例类的正确/最佳/任何方法?我试过这样的事情:

class ScannerGeometry
{
    [int] $EEprom;              # read eeprom
    # ....

    ScannerGeometry()
    {
        # ... fetch calibration from instrument
    }

    [ScannerGeometry] Instance() {
        if ($this -eq $null)
        {
            $this = [ScannerGeometry]::new()
        }
        return $this
    }
}

并将其分配给以下内容:
$scanner = [ScannerGeometry]::Instance()

唉,我收到运行时错误 Method invocation failed because [ScannerGeometry] does not contain a method named 'Instance'.
另外,可以在 PS5 类中将构造函数(或任何其他方法)设为私有(private)吗?

最佳答案

您的方法是这样可见的,因为它不是静态的:

[ScannerGeometry]::new() | set x
PS C:\Work> $x | gm


   TypeName: ScannerGeometry

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
Instance    Method     ScannerGeometry Instance()
ToString    Method     string ToString()
EEprom      Property   int EEprom {get;set;}

您需要使用关键字static .在那种情况下 $this无效,因此您必须稍微更改代码。这是代码:
class ScannerGeometry
{
    [int] $EEprom;              # read eeprom


    static [ScannerGeometry] Instance() {
          return [ScannerGeometry]::new()
    }
}

编辑

好的,这是工作代码:
class ScannerGeometry
{
    [int] $EEprom              # read eeprom

    static [ScannerGeometry] $instance


    static [ScannerGeometry] GetInstance() {
          if ([ScannerGeometry]::instance -eq $null) { [ScannerGeometry]::instance = [ScannerGeometry]::new() }
          return [ScannerGeometry]::instance
    }
}

$s = [ScannerGeometry]::GetInstance()

关于Powershell 5 类和单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36751113/

相关文章:

PowerShell Azure Cmdlet 无法识别

powershell - 使用 WMI 获取 IIS6 网站的所有虚拟目录

powershell - 您不能在空值表达式上调用方法

powershell - 将 cmdlet 的结果值存储在 Powershell 中的变量中

sharepoint - 我的SharePoint内容类型未出现

windows - 如何使用 gnuwin32 Makefile 执行 powershell/cmd 命令?

powershell - 在Powershell 2.0中无法将 “PasswordNeverExpires”参数设置为true

.net - 在 .NET 事件中使用 ref 参数时 PowerShell 崩溃

powershell - 术语 'C:\chefboot_win.ps1'无法识别为cmdlet,函数,脚本文件的名称

Powershell New-SmbMapping 驱动器只能从 Powershell 访问