How to use Reflection [duplicate]

2

How and why to use Reflection? Is it practical in day to day use? Does your use offer any gain for the system itself?

    
asked by anonymous 10.06.2014 / 18:47

1 answer

4
  

There is another question that answers this very well, in more detail, but the purpose of this answer is to be a bit quicker and succinct than the following link:

How and why to use Reflection?

The Reflection , in the .NET Framework, is a feature where you can read an object's data about your class, that is, getting information about:

  • Class properties;
  • Methods;
  • Other values.

It is not unique to the .NET Framework. Other programming languages, such as Java, for example, also have the functionality of Reflection .

Are you very practical on a daily basis?

Many, I would say. The Entity Framework, for example, extensively uses Reflection to map data from a database to objects in a model.

In a code I've developed here, I can read the properties of an object in C # using the following:

    /// <summary>
    /// Extrai as propriedades de um objeto.
    /// </summary>
    /// <param name="objeto"></param>
    /// <returns></returns>
    private IEnumerable<PropertyInfo> ExtrairPropertiesDeObjeto(Object objeto)
    {
        return objeto.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
                               BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
    }

The return will be from a list of PropertyInfo , where I can get the name of the property, its value, the level of protection, etc. In my case, I use to transform the object into an entire SQL statement populated with parameters. It is just a code for all the system tables, and the information in each table is noted as the properties and attributes of a class.

The following code extracts the properties of an object whose class has the attribute [Column] :

    /// <summary>
    /// Obter as colunas da tabela segundo as colunas anotadas com o Atrribute Column.
    /// </summary>
    /// <returns></returns>
    protected IEnumerable<String> ExtrairColunas()
    {
        foreach (var propertyInfo in ExtrairPropertiesDeObjeto(Activator.CreateInstance(typeof(T))))
        {
            var columnAttribute = (ColumnAttribute)propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();
            if (columnAttribute != null)
            {
                yield return columnAttribute.Name;
            }
        }
    }

And the selection is made as follows:

    /// <summary>
    /// 
    /// </summary>
    /// <param name="operadores"></param>
    /// <returns></returns>
    public override IEnumerable<T> Selecionar(IEnumerable<Operador> operadores)
    {
        try
        {
            using (var obj = new Database())
            {
                var sSql =
                    "SELECT ";

                foreach (var coluna in ExtrairColunas())
                {
                    sSql += VirgulaOuEspaco + " t." + coluna;
                }

                sSql += " from " + ExtrairNomeTabela() + " t ";

                foreach (var operador in operadores)
                {
                    sSql += WhereOuAnd + " t." + operador;
                }

                var parametros =
                    operadores.Where(o => o.GetType().IsAssignableFrom(typeof(Igual)))
                        .Select(o2 => ((Igual)o2).ParametroOracle)
                        .ToList();
                var dataTable = obj.ConsultarSQl(ConexaoBancoDados, sSql, parametros);

                return Transliterar(dataTable.Rows);
            }
        }
        finally
        {
            ReiniciarWhereEVirgula();
        }
    }

The whole system uses this method to mount SELECTS . The only thing I pass into the repository class is an object.

Does your use offer any gain for the system itself?

I'd say that's a rhetorical question. Reflection offers a range of features and extra capabilities for the application, where the alternative would be to write much more code.

The basis of current Frameworks is above all% w / w%.

    
10.06.2014 / 18:50