This post originated from an RSS feed registered with .NET Buzz
by Adrian Florea.
Original Post: L'ordine degli attributi multi-use in C#, VB, J#
Feed Title: Web Log di Adrian Florea
Feed URL: /error.aspx?aspxerrorpath=/adrian/Rss.aspx
Feed Description: "You know you've achieved perfection in design, not when you have nothing more to add, but when you have nothing more to take away." Antoine de Saint-Exupery
Ogni compilatore è libero di ordinare l'elenco di attributi multi-use che decorano un elemento di codice in base alle sue proprie regole. In questo senso, le specifiche di C# avvertono: "The order in which attributes are specified in an attribute section, and the order in which sections attached to the same program entity are arranged, is not significant" (ECMA-334, 24.2).
I seguenti 3 snippet equivalenti, scritti rispettivamente in C#, VB e J#:
using System; [Foo(1), Foo(2), Foo(3), Foo(4), Foo(5), Foo(6), Foo(7), Foo(8), Foo(9), Foo(10)] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] classFooAttribute : Attribute { public FooAttribute(int index) { _index = index; } privateint _index; publicint Index { get { return _index; } } staticvoid Main() { Type fooAttributeType = typeof(FooAttribute); foreach (FooAttribute attribute in fooAttributeType.GetCustomAttributes(fooAttributeType, false)) { Console.WriteLine(attribute.Index); } } }
Imports System <Foo(1), Foo(2), Foo(3), Foo(4), Foo(5), Foo(6), Foo(7), Foo(8), Foo(9), Foo(10)> _ <AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)> _ Class FooAttribute Inherits Attribute PublicSubNew(ByVal index AsInteger) _index = index EndSub Private _index AsInteger PublicReadOnlyProperty Index() AsInteger Get Return _index EndGet EndProperty SharedSub Main() Dim fooAttributeType As Type = GetType(FooAttribute) ForEach attribute As FooAttribute In fooAttributeType.GetCustomAttributes(fooAttributeType, False) Console.WriteLine(attribute.Index) Next EndSub EndClass
Tra i tre compilatori, solo quello per J# sembra che non cambi l'ordine. Importante è non presupporre alcun ordine nell'elenco di attributi multi-use in una decorazione.