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.
Callback by Delegate Delegate provides a way to pass a method as argument to other method. To create a Callback in C#, function address will be passed inside a variable. So, this can be achieved by using Delegate.
Understanding delegates in C#Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.
A callback is a function that will be called when a process is done executing a specific task. The usage of a callback is usually in asynchronous logic. To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegate or the new lambda semantic Func or Action .
Working code via Adam's and Oisin's chat.
Add-Type -Language CSharpVersion3 -TypeDefinition @"
using System;
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());
}
}
"@
$method = [Class2].GetMethod("Callback")
$delegate = [System.Delegate]::CreateDelegate([System.Action[Object]], $null, $method)
[Class1]::MyMethod($delegate)
$code = @'
using System;
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());
}
}
'@
Add-Type -TypeDefinition $code -Language CSharpVersion3
[class1]::mymethod([system.action]::CreateDelegate('System.Action[Object]', [class2].getmethod('Callback')))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With