Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide a .NET method as a delegate 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.

like image 803
Adam Driscoll Avatar asked Apr 03 '11 15:04

Adam Driscoll


People also ask

Can delegate be used as callbacks?

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.

Is C# delegate a callback?

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.

What is callback method C#?

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 .


2 Answers

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)
like image 115
Doug Finke Avatar answered Oct 07 '22 17:10

Doug Finke


$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')))
like image 42
Steven Murawski Avatar answered Oct 07 '22 16:10

Steven Murawski