如何在内联 class 方法调用中嵌套函数调用

How to nest function call in class method call inline

class TestClass
{
    TestClass([string]$msg) {
        Write-Host "Ctor sees: $msg"
    }
    TestMethod([string]$msg) {
        Write-Host "TestMethod sees: $msg"
    }
}

# this works:
$x = Get-Date
$test1 = [TestClass]::new($x)

# this also works:
$x = Get-Date
$test1.TestMethod($x)

# but doing the same thing inline is a syntax error: Missing ')' in method call.
$test2 = [TestClass]::new(Get-Date)
$test2 = [TestClass]::new(Get-Date())
$test1.TestMethod(Get-Date)

不言自明;我不想在将参数传递给方法之前必须使用临时变量来存储参数。

我觉得只有一些语法可以使失败的示例按预期工作。

失败的测试在 Get-Date 周围缺少括号。

$test2 = [TestClass]::new((Get-Date))

之所以有效,是因为现在 Get-Date 结果 首先被评估,并且因为您的 class 函数需要 [string],它们会自动由 PowerShell 字符串化。和你做的一样

$test2 = [TestClass]::new((Get-Date).ToString())