我正在使用 Powershell 构建一个自动化系统,并且我想定义自定义 .Net 类型,以便我可以以与我编写的其他代码类似的方式构建我的应用程序。
起初,我尝试使用‘ 添加类型 ' 将类型从 c# 文件导入到我的应用程序中,但我发现调试起来非常痛苦,因为 .net 类型只能在每个 Powershell session 期间加载一次。这意味着当我的代码出现错误时,我需要重新启动我的应用程序(我可能会使用 C#)。
目前,我正在通过使用工厂函数来模拟 Powershell 中的类型,这些函数可以动态生成具有我需要的语义的 PSObject。这确实有效,但它非常冗长,我似乎无法声明私有(private)变量或封装方法。
有没有更简单的方法来实现我想要的?
如果不....
我是否想使用抽象数据类型编写我的 Powershell 代码,从而以某种方式吠叫错误的树?
有没有更好的方法来构建我应该知道的系统?
我可以用我现在正在做的事情来实现一些封装吗?
最佳答案
1) 我没试过,但这个项目看起来很有希望:PSClass - Object Oriented Scripting in Powershell .它提供的一些功能:
PsClass is currently implemented in Powershell in a single file. Makes it simple to use. It supports the following OO concepts.
- Inheritance
- Polymorphism
- Encapsulation
- Constructors with parameters
- Notes – read-write variables
- Methods – scriptblocks
- Properties with Get scriptblocks and optional Set scriptblocks
- Static and Private Notes and Methods
2) 您可以使用这样的自定义模块:
$o = New-Module -AsCustomObject -Function GetVar, AddToVar {
$script:var = 1
function checkRange { if ($var -gt 3 -or $var -lt 0) { throw 'not in range <0,3>' } }
function GetVar { $script:var }
function AddToVar { param($add) checkRange; $script:var += $add; $script:var }
}
$o.GetVar()
$o.AddToVar(2)
$o.AddToVar(1)
$o.GetVar()
$o.checkRange()
$o | gm
尝试将其复制到您的 ide/console 并运行它。
$script:var
是只能在函数中使用的私有(private)成员 GetVar
, AddToVar
. checkRange
也是私有(private)的。如果我需要真正的 OOP(在 C# 中可用),我个人不会使用 PowerShell 来完成这样的任务。 PowerShell 对对象有一些支持,但对 OOP 的支持很差。
关于powershell - 有没有更好的方法在 Powershell 中获取 ‘class’ 语义(定义自定义类型)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3462024/