Convert C# `using` and `new` to PowerShell [closed]

♀尐吖头ヾ 提交于 2021-01-07 06:34:15

问题


There are many codes in C# that use the keywords using and new. They look very simple!

How to achieve that in in PowerShell elegantly!

For example I want to change the following C# code to PowerShell

using (var image = new MagickImage(new MagickColor("#ff00ff"), 512, 128))
{
    new Drawables()
      // Draw text on the image
      .FontPointSize(72)
      .Font("Comic Sans")
      .StrokeColor(new MagickColor("yellow"))
      .FillColor(MagickColors.Orange)
      .TextAlignment(TextAlignment.Center)
      .Text(256, 64, "Magick.NET")
      // Add an ellipse
      .StrokeColor(new MagickColor(0, Quantum.Max, 0))
      .FillColor(MagickColors.SaddleBrown)
      .Ellipse(256, 96, 192, 8, 0, 360)
      .Draw(image);
}

It is difficult to write the new expression because it contains one another! What elegant solution is there?


回答1:


C# using is just syntactic sugar for try {} finally {} so you can do the same in PowerShell. The disposal of the object will be put in the finally block. new can be replaced with New-Object. Of course new can be made an alias to New-Object but MS chose not to

try {
    $color = New-Object MagickColor -ArgumentList (,"#ff00ff")
    $image = New-Object MagickImage -ArgumentList ($color, 512, 128)
    $drawable = New-Object Drawables
    $drawable.FontPointSize(72). `
              Font("Comic Sans"). `
              StrokeColor(New-Object MagickColor -ArgumentList (,"yellow")). `
              FillColor()...
}
finally {
    if ($image) { $image.Dispose() }
    # or just `$image?.Dispose()` in PowerShell 7.1+
}

See

  • About Try Catch Finally
  • using statement (C# Reference)


来源:https://stackoverflow.com/questions/65261346/convert-c-sharp-using-and-new-to-powershell

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