powershell - 在 Add-Type:d C# 代码中使用委托声明会导致方法不可调用
问题描述
在 powershell 中向 C# 代码添加委托似乎失败了,我的问题是为什么以及是否有任何解决方法可以使其正常工作(使用Func
orAction
除外)
测试用例:
$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<>
改用,但在这种情况下,它会减少我希望尽可能拥有的自我文档。
解决方案
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
推荐阅读
- python - How to capture table in a structured format from this website using Beautiful soup and Pandas?
- python - UFuncTypeError: ufunc 'absolute' 不包含签名匹配类型 dtype('
dtype(' 下面的代码循环存储在出队(双端队列)中的一组点。
import numpy as np pts1_blue=[(230,50),(100,200),.....] #this is just example values of the centroids for i in ra
- python - 调用时 urllib 和 urlparse 的问题
- postgresql - jsonb数组上的postgres触发函数if语句
- firebase - Firestore:如何在强制执行唯一字段值的同时插入具有自动 ID 的文档?
- r - 通过两个因素在组内创建 ID
- python - 如何将此列转换为数字?
- reactjs - 如何将 Ziggy 与 React 和 Inertia 一起使用
- javascript - Javascript中的二维数组
- node.js - Create React App 提供的 react-scripts 包需要依赖:“jest”:“24.9.0”?