[英]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.我正在尝试使用 do.net 7 Reflection.Emit 来创建 Dymamic Dll。
I would like to create an Assembly which has a list of string (or Class Type) propery like below;我想创建一个程序集,其中包含如下所示的字符串(或 Class 类型)属性列表;
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.实际上问题是我不知道如何将 List 属性添加到复杂类型。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.