Using model annotations for C #

1

I have this annotation in my model

[ZoneamentoDados(fim = 2, inicio = 1, tamanho = 2, obs = "Tipo Registro")]
public String tipoRegistro { get; set; }
[ZoneamentoDados(fim = 54, inicio = 54, tamanho = 1, obs = "Sempre 1")]

I need to use the end, start, and size values to separate substring and controller . Can anyone tell me how I could use these annotations in controller or indicate some link to understand better?

    
asked by anonymous 16.01.2017 / 13:17

1 answer

1

In this case you will have to work with the famous Reflection .

For this, you will need to read the selected property and return the desired value.

An example would look something like this:

public static int ObterValorInicio<T>(Expression<Func<T>> expr)
{
    var mexpr = expr.Body as MemberExpression;
    if (mexpr == null) return 0;
    if (mexpr.Member == null) return 0;
    //Busco o CustomAttribute ZoneamentoDados
    object[] attrs = mexpr.Member.GetCustomAttributes(typeof(ZoneamentoDados), false);
    if (attrs == null || attrs.Length == 0) return 0;
    //Seleciono o primeiro valor
    ZoneamentoDados desc = attrs[0] as ZoneamentoDados;
    if (desc == null) return 0;

    //Obtém o valor Inicio. Para obter outros valores, basta alterar, ex: return desc.Tamanho;
    return desc.Inicio;
}

In this example I look for a custom attribute called ZoneamentoDados and return the values. If I find the value, I return the value corresponding to the desired property.

See the full .NETFiddle here

Below are some references for better understanding:

16.01.2017 / 14:26