Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Created October 25, 2012 03:57
Show Gist options
  • Save davidfowl/3950340 to your computer and use it in GitHub Desktop.
Save davidfowl/3950340 to your computer and use it in GitHub Desktop.
Expression Redux
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ConsoleApplication5
{
interface IConsume<TMessage>
{
void Consume(TMessage message);
}
class Consumer : IConsume<int>
{
public void Consume(int message)
{
Console.WriteLine("Here's " + message);
}
}
class Program
{
static void Main(string[] args)
{
var c = new Consumer();
var consume = CreateConsumerDelegate<int>(c);
consume(c, 1);
}
private static Action<object, object> CreateConsumerDelegate<TMessage>(object consumer)
{
// Action<object, object> consume = (instance, arg) => ((Type)instance).Consume((TMessage)arg)
var instance = Expression.Parameter(typeof(object));
var arg = Expression.Parameter(typeof(object));
var method = consumer.GetType().GetMethod("Consume");
var convertedInstance = Expression.Convert(arg, consumer.GetType());
var convertedArg = Expression.Convert(instance, typeof(TMessage));
var call = Expression.Call(convertedInstance, method, convertedArg);
var func = Expression.Lambda<Action<object, object>>(call, arg, instance);
return func.Compile();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment