Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Metadata. Data about your objects/methods/properties. </p> <p>For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriately.</p> <pre><code>public class DisplayWrapper { private UnderlyingClass underlyingObject; public DisplayWrapper(UnderlyingClass u) { underlyingObject = u; } [DisplayOrder(1)] public int SomeInt { get { return underlyingObject .SomeInt; } } [DisplayOrder(2)] public DateTime SomeDate { get { return underlyingObject .SomeDate; } } } </code></pre> <p>Thereby ensuring that SomeInt is always displayed before SomeDate when working with my custom GUI components.</p> <p>However, you'll see them most commonly used outside of the direct coding environment. For example the Windows Designer uses them extensively so it knows how to deal with custom made objects. Using the BrowsableAttribute like so:</p> <pre><code>[Browsable(false)] public SomeCustomType DontShowThisInTheDesigner { get{/*do something*/} } </code></pre> <p>Tells the designer not to list this in the available properties in the Properties window at design time for example.</p> <p>You <em>could</em> also use them for code-generation, pre-compile operations (such as Post-Sharp) or run-time operations such as Reflection.Emit. For example, you could write a bit of code for profiling that transparently wrapped every single call your code makes and times it. You could "opt-out" of the timing via an attribute that you place on particular methods.</p> <pre><code>public void SomeProfilingMethod(MethodInfo targetMethod, object target, params object[] args) { bool time = true; foreach (Attribute a in target.GetCustomAttributes()) { if (a.GetType() is NoTimingAttribute) { time = false; break; } } if (time) { StopWatch stopWatch = new StopWatch(); stopWatch.Start(); targetMethod.Invoke(target, args); stopWatch.Stop(); HandleTimingOutput(targetMethod, stopWatch.Duration); } else { targetMethod.Invoke(target, args); } } </code></pre> <p>Declaring them is easy, just make a class that inherits from Attribute. </p> <pre><code>public class DisplayOrderAttribute : Attribute { private int order; public DisplayOrderAttribute(int order) { this.order = order; } public int Order { get { return order; } } } </code></pre> <p>And remember that when you use the attribute you can omit the suffix "attribute" the compiler will add that for you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload