Can attributes be added dynamically in C#?

后端 未结 10 972
别跟我提以往
别跟我提以往 2020-11-22 14:32

Is it possible to add attributes at runtime or to change the value of an attribute at runtime?

10条回答
  •  梦谈多话
    2020-11-22 15:00

    I tried very hard with System.ComponentModel.TypeDescriptor without success. That does not means it can't work but I would like to see code for that.

    In counter part, I wanted to change some Attribute values. I did 2 functions which work fine for that purpose.

            // ************************************************************************
            public static void SetObjectPropertyDescription(this Type typeOfObject, string propertyName,  string description)
            {
                PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName];
                var att = pd.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
                if (att != null)
                {
                    var fieldDescription = att.GetType().GetField("description", BindingFlags.NonPublic | BindingFlags.Instance);
                    if (fieldDescription != null)
                    {
                        fieldDescription.SetValue(att, description);
                    }
                }
            }
    
            // ************************************************************************
            public static void SetPropertyAttributReadOnly(this Type typeOfObject, string propertyName, bool isReadOnly)
            {
                PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName];
                var att = pd.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
                if (att != null)
                {
                    var fieldDescription = att.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
                    if (fieldDescription != null)
                    {
                        fieldDescription.SetValue(att, isReadOnly);
                    }
                }
            }
    

提交回复
热议问题