I need to generate a new interface at run-time with all the same members as an existing interface, except that I will be putting different attributes on some of the methods (some of the attribute parameters are not known until run-time). How can it be achieved?
To dynamically create an assembly with an interface that has attributes:
using System.Reflection;
using System.Reflection.Emit;
// Need the output the assembly to a specific directory
string outputdir = "F:\\tmp\\";
string fname = "Hello.World.dll";
// Define the assembly name
AssemblyName bAssemblyName = new AssemblyName();
bAssemblyName.Name = "Hello.World";
bAssemblyName.Version = new system.Version(1,2,3,4);
// Define the new assembly and module
AssemblyBuilder bAssembly = System.AppDomain.CurrentDomain.DefineDynamicAssembly(bAssemblyName, AssemblyBuilderAccess.Save, outputdir);
ModuleBuilder bModule = bAssembly.DefineDynamicModule(fname, true);
TypeBuilder tInterface = bModule.DefineType("IFoo", TypeAttributes.Interface | TypeAttributes.Public);
ConstructorInfo con = typeof(FunAttribute).GetConstructor(new Type[] { typeof(string) });
CustomAttributeBuilder cab = new CustomAttributeBuilder(con, new object[] { "Hello" });
tInterface.SetCustomAttribute(cab);
Type tInt = tInterface.CreateType();
bAssembly.Save(fname);
That creates the following:
namespace Hello.World
{
[Fun("Hello")]
public interface IFoo
{}
}
Adding methods use the MethodBuilder class by calling TypeBuilder.DefineMethod.
Your question isn't very specific. If you update it with more information, I'll flesh out this answer with additional detail.
Here's an overview of the manual steps involved.
TypeAttributes.Interface
to make your type an interface.TypeBuilder.CreateType
to finish building your interface.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