How to define self referenced collection property ? Type I want to build with Reflection Type Builder.
public class Sample
{
public Sample()
{
Items = new List<Sample>();
}
public List<Sample> Items { get; set; }
Public void AddSample(Sample item)
{
items.Add(item);
}
}
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();
Activator.CreateInstance(type);
myAssembly.Save(myAsmName.Name + ".dll");
You have to define manually the "backing field" by emitting field and define getter and setter for your property.