How to use Reflection

Asked

Viewed 247 times

2

How and why to use Reflection? Is it very useful in everyday life? Its use offers some gain for the system itself?

  • Excellent question (already favorite). I think it applies not only to the world . NET but to other platforms like Java as well.

1 answer

4


There is another question that answers this very well, with more details, but the purpose of this answer is to be a little faster and more succinct than the following link: What is Reflection, why is it useful? How to use?

How and why to use Reflection?

The Reflection, in Framework . NET, is a feature in which it is possible to read the data of an object as to its class, that is, to obtain information about:

  • Class properties;
  • Methods;
  • Other values.

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

Has much practical use in everyday life?

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

In a code I developed here, I can read the properties of a C# object 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 it to turn the object into an entire SQL sentence filled with parameters. It is just a code for all tables in the system, and the information of each table is annotated as properties and attributes of a class.

The following code extracts the properties of an object whose class is with 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 entire system uses this method to mount SELECTS. The only thing I pass to the repository class is an object.

Its use offers some gain for the system itself?

I would say that is a rhetorical question. The 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 Reflection.

  • This question was asked, because sometimes I do not see practicality to know properties of an object and its type, because I have declared it in my code.

  • @pnet Good, if necessary, I can give examples of how to do.

  • It is always good, although it is clear that the intention here is not to see code, but rather to learn and abstract everything about what has been asked. But having a practical example is always good yes. I will change work and where I go, I need these concepts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.