如何在C#中编写try-get函数?

时间:2016-02-07 13:49:45

标签: .net windows powershell scripting

我正在编写一个PowerShell脚本,如果它尚未加载,则会加载它。我在C#中的逻辑如下:

void DoSomething(string assemblyFilePath)
{
    string name = Path.GetFileNameWithoutExtension(assemblyFilePath);

    Assembly assemblyObject;
    if (!TryGetAssembly(name, out assemblyObject))
    {
        assemblyObject = LoadAssemblyFrom(assemblyFilePath);
    }

    // Do something with assemblyObject.
}

我正在尝试将其转换为PowerShell,但到目前为止还没有成功。这是我的进步:

function TryGet-Assembly($assembly, [ref] $cached)
{
    $domain = [AppDomain]::CurrentDomain

    foreach ($reference in $domain.GetAssemblies())
    {
        # GetName() has a type of AssemblyName,
        # so we need to use GetName().Name to get a string
        $name = $reference.GetName().Name
        if ($name -eq $assembly)
        {
            $cached = $reference
            return $true
        }
    }

    return $false
}

function Get-Namespaces($assembly)
{
    # Load the assembly, or retrieve it if it's cached
    $name = [IO.Path]::GetFileNameWithoutExtension($assembly)
    if (-not TryGet-Assembly $name $assemblyObject)
    {
        $assemblyObject = Load-Assembly $assembly
    }

    # Do the actual work
    $types = $assemblyObject.GetTypes()
    return $types | ? IsPublic | select Namespace -Unique
}

出于某种原因,当PowerShell尝试运行脚本时,我似乎遇到了语法错误。这是输出:

At C:\Users\James\Code\csharp\Shims.Xaml\generate.ps1:83 char:13
+     if (-not TryGet-Assembly $name $assemblyObject)
+             ~
Missing expression after unary operator '-not'.
At C:\Users\James\Code\csharp\Shims.Xaml\generate.ps1:83 char:14
+     if (-not TryGet-Assembly $name $assemblyObject)
+              ~~~~~~~~~~~~~~~
Unexpected token 'TryGet-Assembly' in expression or statement.
At C:\Users\James\Code\csharp\Shims.Xaml\generate.ps1:83 char:14
+     if (-not TryGet-Assembly $name $assemblyObject)
+              ~~~~~~~~~~~~~~~
Missing closing ')' after expression in 'if' statement.
At C:\Users\James\Code\csharp\Shims.Xaml\generate.ps1:80 char:1
+ {
+ ~
Missing closing '}' in statement block or type definition.
At C:\Users\James\Code\csharp\Shims.Xaml\generate.ps1:83 char:51
+     if (-not TryGet-Assembly $name $assemblyObject)
+                                                   ~
Unexpected token ')' in expression or statement.
At C:\Users\James\Code\csharp\Shims.Xaml\generate.ps1:91 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : MissingExpressionAfterOperator

为什么会发生这种情况,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

由于函数调用通常在PowerShell中没有括号,这会产生令人遗憾的影响,即运算符优先级看起来不像其他语言那样有用。

特别是-not(或!)运算符通常要求将其操作数完全包装在括号内:

if (-not (TryGet-Assembly $name $assemblyObject))

或使用!的替代别名-not

if (!(TryGet-Assembly $name $assemblyObject))

我个人更喜欢明确的-not,因为在这些括号中更明显。