Use string to reference variable

Asked

Viewed 160 times

1

I wish to move on to the function execSQL the name of the variable I want to use in base.consulta() and from the string SQL, directly pass the variable to the function base.consulta(), that is, pass the variable that has the same name as the string.

An example for you to have an idea of what I’m looking for.

OBS: I know the way it is doesn’t work and I know why.

// variáveis com algum SQL
string sqlConsultaEspecifica = "...";
string sqlMonitoramento = "...";
string sqlVerificacao = "...";

function execSQL(string sql = "sqlMonitoramento") {
  // ...
  // realizar algumas ações aqui
  // ...
  return base.consulta(sql);
}

Is it possible to do this? How could I do this?

  • Create a class, add the sql commands in constants, by calling the function pass the constant in the parameter, equivalent to what @Maniero said below.

3 answers

1


First of all this syntax is not C#.

It is always possible to build a sophisticated mechanism that allows this. But for what?

One of the ways is to use reflection, but almost 100% of the cases that one uses reflection is doing something wrong. It is a tremendous complication, a huge loss of performance, chance of failure, of insecurities for a gain that is often small or zero. I can almost guarantee you that this case is zero.

Where is the call of that method execSQL()? It is there where you will define what to pass. If the method already knows what it wants, then it makes no sense to use this.

If these variables are local to a method, it makes zero sense to try to do something like this. If the variables are of the object it is quite simple:

void ExecSQL() {
    ...
    return base.consulta(sqlMonitoramento);
}

If it is a local variable the reflection does not work. If it is a class variable or instance the reflection is unnecessary, zero gain.

If you want to do things differently, go to string different.

void ExecSQL(string sql) {
    ...
    return base.consulta(sql);
}

There to call you pass, for example:

ExecSQL(sqlMonitoramento);

I put in the Github for future reference.

This code is very strange and may have an architectural flaw there. I can’t say because it has no context.

  • I thought of something using Enum, Description and an extension method, but I asked myself the same question "It is always possible to build a sophisticated mechanism that allows this. But what for?" and I also thought it would be a bit of a gambiarra :p

  • This solution already seems a little better than reflection and may have felt, but in this case I have not seen reason.

  • This function is in the DAO where I also add some variables with the sql that I will use. And in the Controller part I call this function execSQL passing the name of the variable that contains the desired sql.

  • I mean, it’s simple, and you want to complicate?

  • I was thinking of "simplicate". A function to call any registered sql.

  • No, you’re complicating, what I’ve done is the simplest there is.

Show 1 more comment

0

To obtain the value of a variable of some object it is possible to do as follows:

Imagine an object named "Test" with 2 properties (Description and Name).

Let’s say I want to take the value of some of these two properties, but I still don’t know which, so follow an example code with one of the ways to solve this.

Teste teste = new Teste()
        {
            Descricao = "Descrição aqui",
            Nome = "nome aqui"
        };

        string valorDesejado = teste.GetType().GetProperty("Descricao").GetValue(teste, null).ToString();

Inside the "Getproperty()" goes the name of the variable that I want to get the value. So just adapt.

  • But you know what the property is there, it’s very explicit in the code. Just like in the question.

0

You can try this way:

public void execSQL(string sql)
{
    //A variável "valor" vai estar com o valor da variável que você passou como parâmetro.
    //O objeto "classe" deve ser o objeto que possui a sua variável "sql"
    string valor = teste.GetType().GetProperty(sql).GetValue(classe, null).ToString()   
}

The call to the method would look like this:

//Aqui você iria passar a variável que gostaria de passar o nome para o método, porém ela deve ser visível para esse escopo
execSQL(nameof(sqlMonitoramento));
  • See my answer. Much simpler and does exactly the same thing.

Browser other questions tagged

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