简体   繁体   中英

how to define List<Foo> as a property of Type by using AssemblyBuilder and TypeBuilder in dotnet Core 7?

I'm trying to crate Dymamic Dll by using do.net 7 Reflection.Emit.

I would like to create an Assembly which has a list of string (or Class Type) propery like below;

 private List<string> Items;
// OR 
 private List<Foo> Items;

And This is the code I'm using to add any property to a Type.

 AssemblyGeneratorHelper.AddProperty(dynamicType, "Items", typeof(List<string>));

This is the my my Helper method.

public static void AddProperty(TypeBuilder typeBuilder, string propertyName, Type propertyType)
    {
        var fieldBuilder = typeBuilder.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
        var propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);

        var getMethod = typeBuilder.DefineMethod("get_" + propertyName,
            MethodAttributes.Public |
            MethodAttributes.SpecialName |
            MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
        var getMethodIL = getMethod.GetILGenerator();
        getMethodIL.Emit(OpCodes.Ldarg_0);
        getMethodIL.Emit(OpCodes.Ldfld, fieldBuilder);
        getMethodIL.Emit(OpCodes.Ret);

        var setMethod = typeBuilder.DefineMethod("set_" + propertyName,
              MethodAttributes.Public |
              MethodAttributes.SpecialName |
              MethodAttributes.HideBySig,
              null, new[] { propertyType });
        var setMethodIL = setMethod.GetILGenerator();
        Label modifyProperty = setMethodIL.DefineLabel();
        Label exitSet = setMethodIL.DefineLabel();

        setMethodIL.MarkLabel(modifyProperty);
        setMethodIL.Emit(OpCodes.Ldarg_0);
        setMethodIL.Emit(OpCodes.Ldarg_1);
        setMethodIL.Emit(OpCodes.Stfld, fieldBuilder);
        setMethodIL.Emit(OpCodes.Nop);
        setMethodIL.MarkLabel(exitSet);
        setMethodIL.Emit(OpCodes.Ret);

        propertyBuilder.SetGetMethod(getMethod);
        propertyBuilder.SetSetMethod(setMethod);
    }

This Code is running successfully. But when I try to use generated Assembly I'm getting error shown like below. 在此处输入图像描述

Actually problem is I don't know how to add List property to a complex type. I think there is an other way to use instead of

AssemblyGeneratorHelper.AddProperty(dynamicType, "Items",typeof(List<string>));

This is how I solved the problem. It works as I expected.

    Type t1= typeof(Foo).MakeArrayType();
    // OR 
    Type t2 = typeof(string).MakeArrayType();

AssemblyGeneratorHelper.AddProperty(dynamicType, "Items", t1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM