This is a mirror of official site: http://jasper-net.blogspot.com/

Getting started with attributes – part V

| Sunday, July 24, 2011
After all, I’ve decided to write another post about custom attributes. In the last post, I’ve mentioned the use of the CustomAttributeData type. Since I’ve received a couple of questions about its use, I thought it would be a good idea to show an example of how one can use this class to check for specific values. So, I’ll just start by introducing the custom attribute and some code that applies it to a property:

class MyAttribute:Attribute {

    public MyAttribute( string someValue ) {
        SomeValue = someValue;
    }

    publicString SomeValue { get; privateset; }

    publicString SomeOtherValue { get; set; }
}

classStudent {

    [My("Howdy", SomeOtherValue = "there!")]
    publicString Nome { get; set; }

    publicString Morada { get; set; }
}

In the previous post, we’ve already saw how to check if an attribute is applied to a specific target. So, we won’t be performing that check again and I’ll just show you how to recover the values applied to the properties of the attribute:
var prop = typeof( Student ).GetProperty( “Nome” );

var attrib = CustomAttributeData.GetCustomAttributes( prop ).First();

//positional arguments can be obtained from the ConstructorArguments prop
var positionalArgs = attrib.ConstructorArguments;

for(var i = 0; i < positionalArgs.Count; i++){
    Console.WriteLine( “arg at pos {0} has value {1}“,
        i, positionalArgs[i].Value);
}


Read more: LA.NET [EN]
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://blogs.msmvps.com/luisabreu/blog/2011/07/21/getting-started-with-attributes-part-v/

Posted via email from Jasper-net

0 comments: