【问题标题】:Attach existing CustomAttribute to field using C#使用 C# 将现有的 CustomAttribute 附加到字段
【发布时间】: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


【解决方案1】:

你可以为你的属性构造一个CustomAttributeBuilder

Type[] ctorParams = new Type[] { /*Types of your Attributes Constructor*/ };
ConstructorInfo classCtorInfo = typeof(ColumnAttribute).GetConstructor(ctorParams);

CustomAttributeBuilder myCABuilder = new CustomAttributeBuilder(
                        classCtorInfo,
                        /*arguments for your Attribute*/);

propertyBuilder.SetCustomAttribute(myCABuilder);

【讨论】:

  • 谢谢。我有一个现有的 customattribute。我更改了问题以使其更清楚。
【解决方案2】:

这是不可能的。 CustomAttribute 必须动态创建。 有关更多信息,请参阅此问题。 TypeBuilder - Adding attributes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-10
    • 2011-04-15
    • 2017-03-25
    • 2011-10-15
    • 2014-08-07
    • 2011-08-20
    • 2019-02-17
    • 2023-03-27
    相关资源
    最近更新 更多