提供 .NET 方法作为委托回调
在 PowerShell 中将 .NET 方法作为委托回调传递给 .NET 对象的语法是什么。
例如:
C#:
public class Class1
{
public static void MyMethod(Action<object> obj)
{
obj("Hey!");
}
}
public class Class2
{
public static void Callback(object obj)
{
Console.Writeline(obj.ToString());
}
}
PowerShell:
[Class1]::MyMethod([Class2]::Callback)
这不起作用。
What is the syntax to pass .NET method as a delegate callback to a .NET object in PowerShell.
For example:
C#:
public class Class1
{
public static void MyMethod(Action<object> obj)
{
obj("Hey!");
}
}
public class Class2
{
public static void Callback(object obj)
{
Console.Writeline(obj.ToString());
}
}
PowerShell:
[Class1]::MyMethod([Class2]::Callback)
This doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
通过 Adam 和 Oisin 的聊天来工作代码。
Working code via Adam's and Oisin's chat.
通过 Twitter 上的@oising:
Via @oising on Twitter:
[Class2]::Callback
的类型是System.Management.Automation.PSMethod
,显然核心无法将其转换为所需的委托。我不确定这是解决任务的最佳方法(我没有看到任何关于此的官方文档),但下面的代码在这个示例案例和我的实践中的其他类似案例中适用于我:
核心是能够将我们的脚本块
{ [Class2]::Callback($args[0]) }
转换为所需的委托。PS 虽然与问题没有直接关系,但这里是此技术的另一个工作示例:在正则表达式中使用脚本块作为匹配评估器委托:
如何排序文件名与 Windows 资源管理器的名称相同吗?
The type of
[Class2]::Callback
isSystem.Management.Automation.PSMethod
which apparently cannot be converted by the core to the required delegate.I am not sure that this is the best way of solving the task (I have not seen any kind of official documentation about this) but the code below works for me in this example case and other similar cases in my practice:
The core is able to convert our script block
{ [Class2]::Callback($args[0]) }
to the required delegate.P.S. Though not directly related to the question but here is yet another working example of this technique: using script blocks as match evaluator delegates in regular expressions:
How to sort by file name the same way Windows Explorer does?
我不是 C# 专家,但在阅读了几篇文章后,您似乎正在尝试使用通用委托。您的回调方法不是通用委托,它甚至不是委托。
我认为这就是你需要做的:
C#
Powershell:
I am not an expert at C#, but after reading a couple articles it seems that you are trying to use generic delegates. Your Callback method is not a generic delegate, it isn't even a delegate.
I think this is what you need to do:
C#
Powershell: