Share via

using system.reflection.emit to create type with generictype

Conner 6 Reputation points
2022-07-15T10:05:29.917+00:00

i wanna create a type like TypeA
class TypeA
{
List<TypeA> data;
public TypeA()
{
data =new List<TypeA>()
}
}

//here's my code
// the question is i can't the constructor of List<A>
using System.Reflection;
using System.Reflection.Emit;

var assembleBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Dynamic"), AssemblyBuilderAccess.RunAndCollect);
var moduleBuilder = assembleBuilder.DefineDynamicModule("Dynamic.dll");
var typeA = moduleBuilder.DefineType("TypeA");

var dataField=typeA.DefineField("data", typeof(List<>).MakeGenericType(typeA),FieldAttributes.Private);

var ctor=typeA.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);
var ctorIl = ctor.GetILGenerator();
var listctor = typeof(List<>).MakeGenericType(typeA).GetConstructors()[0];
ctorIl.Emit(OpCodes.Newobj, listctor);
ctorIl.Emit(OpCodes.Stfld, dataField);
ctorIl.Emit(OpCodes.Ret);

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.