开发者

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

开发者 https://www.devze.com 2022-12-21 04:04 出处:网络
I have a custom attribute, inside the constructor of my custom attribute I want to set the value of a property of my a开发者_运维问答ttribute to the type of the property my attribute was applied to, i

I have a custom attribute, inside the constructor of my custom attribute I want to set the value of a property of my a开发者_运维问答ttribute to the type of the property my attribute was applied to, is there someway to access the member that the attribute was applied to from inside my attribute class?


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"
    }
}


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消