This post originated from an RSS feed registered with .NET Buzz
by Adrian Florea.
Original Post: Decorando con enum
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
Nello snippet seguente mostro un semplice ma elegante pattern per il wrapping di un'enumeration (ho inserito le spiegazioni come commenti nel codice).
Il fatto che il wrapper deriva da System.Attribute è solo per offrire una situazione concreta in cui il wrapping diventa utile e necessario. Con il valore 0 per il primo elemento dell'enumeration ho voluto ricordare una best practice spesso dimenticata: "ensure that 0 is a valid state for value types" (vedi l'item 8 del libro "Effective C#" di Bill Wagner).
using System; publicenumFooEnum { Something = 0, // Default SomethingElse } publicsealedclassFooAttribute : Attribute { // il campo enumeration su cui si fa il wrapping privatereadonlyFooEnum _Foo; publicFooEnum Foo {get{return _Foo;}} // private perché non è un elemento esplicito dell'enumeration privatestaticreadonlyFooAttribute _Default = FooAttribute.Something; publicstaticreadonlyFooAttribute Something = newFooAttribute(FooEnum.Something); publicstaticreadonlyFooAttribute SomethingElse = newFooAttribute(FooEnum.SomethingElse); // l'enumeration ha un elemento di valore 0 (default) public FooAttribute() : this(newFooEnum()) { } public FooAttribute(FooEnum foo) { _Foo = foo; } publicoverridebool IsDefaultAttribute() { return Equals(FooAttribute._Default); } publicoverridebool Equals(object value) { if (value == this) { returntrue; } if (!(value isFooAttribute)) { returnfalse; } return (((FooAttribute)value).Foo == Foo); } // Equals e GetHashCode ridefiniti insieme, altrimenti warning CS0659 publicoverrideint GetHashCode() { returnbase.GetHashCode(); } // ToString dell'enumeration publicoverridestring ToString() { return Foo.ToString(); } }