Get member to which attribute was applied from inside attribute constructor?

后端 未结 3 1431
遇见更好的自我
遇见更好的自我 2020-11-30 10:11

I have a custom attribute, inside the constructor of my custom attribute I want to set the value of a property of my attribute to the type of the property my attribute was a

相关标签:
3条回答
  • 2020-11-30 10:44

    It's possible from .NET 4.5 using CallerMemberName:

    [SomethingCustom]
    public string MyProperty { get; set; }
    

    Then your attribute:

    [AttributeUsage(AttributeTargets.Property)]
    public class SomethingCustomAttribute : Attribute
    {
        public StartupArgumentAttribute([CallerMemberName] string propName = null)
        {
            // propName = "MyProperty"
        }
    }
    
    0 讨论(0)
  • 2020-11-30 10:48

    Attributes don't work that way, I'm afraid. They are merely "markers", attached to objects, but unable to interact with them.

    Attributes themselves should usually be devoid of behaviour, simply containing meta-data for the type they are attached to. Any behaviour associated with an attribute should be provided by another class which looks for the presence of the attribute and performs a task.

    If you are interested in the type the attribute is applied to, that information will be available at the same time you are reflecting to obtain the attribute.

    0 讨论(0)
  • 2020-11-30 10:51

    You can do next. It is simple example.

    //target class
    public class SomeClass{
    
        [CustomRequired(ErrorMessage = "{0} is required", ProperytName = "DisplayName")]
        public string Link { get; set; }
    
        public string DisplayName { get; set; }
    }
        //custom attribute
        public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
    {
        public string ProperytName { get; set; }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var propertyValue = "Value";
            var parentMetaData = ModelMetadataProviders.Current
                 .GetMetadataForProperties(context.Controller.ViewData.Model, context.Controller.ViewData.Model.GetType());
            var property = parentMetaData.FirstOrDefault(p => p.PropertyName == ProperytName);
            if (property != null)
                propertyValue = property.Model.ToString();
    
            yield return new ModelClientValidationRule
            {
                ErrorMessage = string.Format(ErrorMessage, propertyValue),
                ValidationType = "required"
            };
        }
    }
    
    0 讨论(0)
提交回复
热议问题