Reputation: 71
I'm trying to crate Dymamic Dll by using dotnet 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>));
Upvotes: 0
Views: 48
Reputation: 71
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);
Upvotes: 0