Skip to content

Instantly share code, notes, and snippets.

Created October 9, 2009 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/205833 to your computer and use it in GitHub Desktop.
Save anonymous/205833 to your computer and use it in GitHub Desktop.
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace DP115Test
{
using System;
class Program
{
static void Main(string[] args)
{
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName( "Foo" ), AssemblyBuilderAccess.RunAndSave );
var type = assembly
.DefineDynamicModule( "FooModule", "FooModule.dll", true )
.DefineType( "AClass", TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit, typeof( object ), new[] { typeof( IFoo ) } );
var method = type.DefineMethod("IFoo.SomeMethod", MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, CallingConventions.HasThis);
var typeParameters = method.DefineGenericParameters( new[] { "TBase", "TInherited" } );
typeParameters[ 1 ].SetBaseTypeConstraint( typeParameters[ 0 ] );
method.SetReturnType( typeof( void ) );
method.GetILGenerator().Emit( OpCodes.Ret );
type.DefineMethodOverride( method, typeof( IFoo ).GetMethods().Single() );
var createdType = type.CreateType();
assembly.Save( "FooModule.dll" );
var instance = Activator.CreateInstance( createdType ) as IFoo;
instance.SomeMethod<IComparable<string>, string>();
}
}
public interface IFoo
{
void SomeMethod<TBase, TInherited>() where TInherited : TBase;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment