Wallace, the [HttpGet] and the [Length] sane Attributes, which are how to implement the Decorator Pattern in the .NET.
They are useful when you want to associate some additional information to your class, field, property, etc.
If you want to implement your own Attribute, simply create a class that you inherit 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()
{
}
}
for uses, simply assign an attribute to its 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 little 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 the ASP.NET MVC, an attribute that perhaps it is good for you to know are the Action Filter, for this it is enough to implement the interface IActionFilter 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
{
...
}
http://answall.com/questions/119024/como-criar-um-custom-attribute
– Gabriel Katakura
@Gabrielkatakura I think that answers the question, see
– Wallace Maxters
This in C# is called attribute.
– Laerte
Unfortunately I don’t have time at the moment to formulate an answer, and I don’t like to give answers simply with links.
– Gabriel Katakura
-1 Why is the question duplicated? Duplicate is not useful? Does not reference another question? Ok, right
– Wallace Maxters