Given a property in a class, with attributes - what is the fastest way to determine if it contains a given attribute? For example:
[IsNotNullable] [IsPK] [IsIdentity] [SequenceNameAttribute("Id")] public Int32 Id { get { return _Id; } set { _Id = value; } }
What is the fastest method to determine that for example it has the "IsIdentity" attribute?
The hasAttribute() returns a Boolean value that indicates if the element has the specified attribute. If the element contains an attribute, the hasAttribute() returns true; otherwise, it returns false .
The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);
Advertisements. An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute.
If you are using .NET 3.5 you might try with Expression trees. It is safer than reflection:
class CustomAttribute : Attribute { } class Program { [Custom] public int Id { get; set; } static void Main() { Expression<Func<Program, int>> expression = p => p.Id; var memberExpression = (MemberExpression)expression.Body; bool hasCustomAttribute = memberExpression .Member .GetCustomAttributes(typeof(CustomAttribute), false).Length > 0; } }
There's no fast way to retrieve attributes. But code ought to look like this (credit to Aaronaught):
var t = typeof(YourClass); var pi = t.GetProperty("Id"); var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity));
If you need to retrieve attribute properties then
var t = typeof(YourClass); var pi = t.GetProperty("Id"); var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false); if (attr.Length > 0) { // Use attr[0], you'll need foreach on attr if MultiUse is true }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With