vendredi 9 décembre 2016

How to: Define a Self Referenced Type Property with Reflection Emit in c#

How to define self referenced collection property ? Type I want to build with Reflection Type Builder.

public class Sample
{
    public Sample()
    {
    }
    List<Sample> Items { get; set; }
}

The code I write

AppDomain myDomain = AppDomain.CurrentDomain;
AssemblyName myAsmName = new AssemblyName("GenericEmit");
AssemblyBuilder myAssembly = myDomain.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.RunAndSave);

ModuleBuilder myModule = myAssembly.DefineDynamicModule(myAsmName.Name, myAsmName.Name + ".dll");
TypeBuilder myType = myModule.DefineType("Sample", TypeAttributes.Public);  
Type listOf = typeof(List<>);
Type selfContained = listOf.MakeGenericType(myType);
myType.DefineProperty("Items", PropertyAttributes.None, selfContained, null);                
Type type= myType.CreateType();
myAssembly.Save(myAsmName.Name + ".dll");





Aucun commentaire:

Enregistrer un commentaire