首页 > 解决方案 > 在 Add-Type:d C# 代码中使用委托声明会导致方法不可调用

问题描述

在 powershell 中向 C# 代码添加委托似乎失败了,我的问题是为什么以及是否有任何解决方法可以使其正常工作(使用FuncorAction除外)

测试用例:

$id = get-random
$tester = Add-Type -TypeDefinition @"
using System;

public static class Class$id {
    public static void test()
    {
        Console.WriteLine("test$id");
    }

    private delegate void doStuff(); // comment out this line and we are ok?
}
"@ -Language CSharp -PassThru
$tester
$tester::test()

结果是

PS C:\> $tester

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    Class897305760                           System.Object
False    True     doStuff                                  System.MulticastDelegate


PS C:\> $tester::test()
Method invocation failed because [System.Object[]] does not contain a method named 'test'.
At line:1 char:1
+ $tester::test()
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

删除或注释掉private delegate void doStuff(); 运行正常:

PS C:\> $tester

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    Class883741893                           System.Object


PS C:\> $tester::test()
test883741893

在这里,我们可以看到它doStuff在课堂之外可用,但不确定这是否在某种程度上相关。

我确实打算使用委托,但是重现问题不需要这部分代码,因此将其省略。我目前的解决方法是Action<>改用,但在这种情况下,它会减少我希望尽可能拥有的自我文档。

标签: powershell

解决方案


Add-Type返回Class$ID类型和委托类型 -$tester包含两者的数组也是如此:

$class = $tester |Where Name -like 'Class*' |Select -First 1
$class::test() # this should work now, with or without the delegate

推荐阅读