Skip to content

Instantly share code, notes, and snippets.

@philiplaureano
Last active August 29, 2015 14:04
Show Gist options
  • Save philiplaureano/f481e6b0ec68173d04d9 to your computer and use it in GitHub Desktop.
Save philiplaureano/f481e6b0ec68173d04d9 to your computer and use it in GitHub Desktop.
An example of how to use LinFu's new ability to append extension methods to an existing dynamic type and treat it as if it were an instance method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using LinFu.Finders;
using LinFu.Finders.Interfaces;
using LinFu.Reflection;
using CLRDynamicObject = System.Dynamic.DynamicObject;
namespace DynamicDemo
{
public class Greeter
{
public void Greet()
{
Console.WriteLine("Hello, World!");
}
}
public static class GreeterExtensions
{
public static void SaySomethingElse(this Greeter greeter)
{
Console.WriteLine("Something Else");
}
}
public interface IFoo
{
void SaySomethingElse();
}
class Program
{
static void Main(string[] args)
{
// Note: You can get LinFu.Reflection (aka DynamicObject)
// here: https://www.nuget.org/packages/LinFu.Reflection
var dynamicObject = new DynamicObject(new Greeter());
dynamicObject.AddExtensionClass(typeof (GreeterExtensions));
// Example #1: Mapping the dynamicObject to an interface
// and redirecting the SaySomethingElse() call to the
// extension method
var duck = dynamicObject.CreateDuck<IFoo>();
duck.SaySomethingElse();
// Example #2: Converting LinFu's DynamicObject to
// a CLR DynamicObject and making a late-bound call
// on the SaySomethingElse method in the extension class
dynamic expando = dynamicObject.AsExpandoObject();
expando.SaySomethingElse();
return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment