【发布时间】:2019-03-11 14:08:29
【问题描述】:
我注意到这是 TypeBuilder - Adding attributes 的副本,因此请求关闭。
我有一些代码可以将字段动态添加到 TypeBuilder。 该字段还有一个我想要添加的现有注释/自定义属性。 我该怎么做?
private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType, ColumnAttribute annotation)
{
FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
ILGenerator getIl = getPropMthdBldr.GetILGenerator();
getIl.Emit(OpCodes.Ldarg_0);
getIl.Emit(OpCodes.Ldfld, fieldBuilder);
getIl.Emit(OpCodes.Ret);
MethodBuilder setPropMthdBldr =
tb.DefineMethod("set_" + propertyName,
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig,
null, new[] { propertyType });
ILGenerator setIl = setPropMthdBldr.GetILGenerator();
Label modifyProperty = setIl.DefineLabel();
Label exitSet = setIl.DefineLabel();
setIl.MarkLabel(modifyProperty);
setIl.Emit(OpCodes.Ldarg_0);
setIl.Emit(OpCodes.Ldarg_1);
setIl.Emit(OpCodes.Stfld, fieldBuilder);
setIl.Emit(OpCodes.Nop);
setIl.MarkLabel(exitSet);
setIl.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getPropMthdBldr);
propertyBuilder.SetSetMethod(setPropMthdBldr);
????????
Code the add the annotation to the property here.
}
【问题讨论】:
-
使用
CustomAttributeBuilder。 -
@thehennyy 这就是我一直在尝试做的。可以举个例子吗?
-
如果您尝试过,请提供无效的代码。 msdn 包含完整示例:docs.microsoft.com/de-de/dotnet/api/…
-
参数列表中的
ColumnAttribute是错字吗? -
@Ackdari 这是一个类名。应添加到属性的 customattribute。
标签: c# reflection custom-attributes