Wallace, [HttpGet]
and [Length]
are Attributes
, which are how to implement the Decorator Pattern
no .NET
.
They are useful when you want to associate some additional information with your class, field, property, etc.
If you want to implement your own Attribute, simply create a class that inherits directly or indirectly from System.Attribute
, as in the examples below.
[AttributeUsage(AttributeTargets.Class)]
public class ClassInfoAttribute : System.Attribute
{
public string Namespace { get; set; }
public string Name { get; set; }
public ClassInfoAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class FieldInfoAttribute : System.Attribute
{
public string DataType { get; set; }
public string Name { get; set; }
public FieldInfoAttribute()
{
}
}
To use them, simply assign an attribute on your class, field, property with the name of the Attribute (without the Attribute).
[ClassInfo(Namespace = "Meu Namespace", Name = "Minha Classe")]
public class MinhaClasse
{
[FieldInfo(DataType = "Texto", Name = "Minha Propriedade")]
public string MinhaPropriedade { get; set; }
[FieldInfo(DataType = "Texto", Name = "Meu Campo")]
public string meuCampo;
public MinhaClasse()
{
}
}
If you need to retrieve the attribute, you will need to use a bit of System.Reflection
var classe = new MinhaClasse();
var tipo = classe.GetType();
var campo = tipo.GetField("meuCampo");
var propriedade = tipo.GetProperty("MinhaPropriedade");
var classIndo = (ClassInfoAttribute)tipo.GetCustomAttributes(typeof(ClassInfoAttribute), false);
var fieldInfo = (FieldInfoAttribute)campo.GetCustomAttributes(typeof(FieldInfoAttribute), false);
var propertyInfo = (FieldInfoAttribute)propriedade.GetCustomAttributes(typeof(FieldInfoAttribute), false);
Since you mentioned ASP.NET MVC
, an attribute that you might know is Action Filter
, so just implement the IActionFilter
interface and inherit from ActionFilterAttribute
.
public class MeuFiltroAttribute : ActionFilterAttribute, IActionFilter
{
void OnActionExecuting(ActionExecutingContext filterContext) { ... }
void OnActionExecuted(ActionExecutingContext filterContext) { ... }
void OnResultExecuting(ResultExecutingContext filterContext) { ... }
void OnResultExecuted(ResultExecutedContext filterContext) { ... }
}
[MeuFiltro]
public class MinhaController : Controller
{
...
}