How to get a value using interpolation?

Asked

Viewed 65 times

2

I am trying to recover a class value using interpolation. Using Console.WriteLine($"Meu Nome é, {pessoa.Nome}");, I get the value of the form I want, but in my case the string will come from a database configuration.

I tried to ride it like this

string expressao = "Meu Nome é,  {pessoa.Nome}";

and call it that

Console.WriteLine($"" + (expressao));

This prints the string

My Name is, {person. Name}

And that’s not what I want. Is there any way to do that?

using System;

namespace Usando_Interpolacao
{
    class Program
    {
        static void Main(string[] args)
        {
            var pessoa = new Pessoa()
            {
                Documento = new Documento()
                {
                    Numero = 12345,
                    Tipo = "RG"
                },
                Idade = 20,
                Nome = "Papai Noel",
            };

            string expressao = "Meu Nome é,  {pessoa.Nome}";

            Console.WriteLine($"Meu Nome é,  {pessoa.Nome}"); // print --> Meu Nome é,  Papai Noel
            Console.WriteLine($"" + (expressao)); // print --> Meu Nome é,  {pessoa.Nome} .. Errado :(
            Console.ReadKey();
        }
    }

    public class Pessoa
    {
        public int Idade { get; set; }
        public string Nome { get; set; }
        public Documento Documento { get; set; }
    }

    public class Documento
    {
        public int Numero { get; set; }
        public string Tipo { get; set; }
    }
}
  • and expressao = $"Meu Nome é, {pessoa.Nome}"; dps, Console.WriteLine(expressao); ?

  • There is no way because interpolation is solved at compile time. That is, tokens need to be known beforehand. The final code is a string.Format default. What you can do is build a method to dynamically solve tokens.

  • 1
  • You need something that does the "parse" or "evaluate" of your expression for that. Take a look at this package that does just that: https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples

  • With this package, your code would look like this: var resultado = await CSharpScript.EvaluateAsync<string>(expressao);

  • @LINQ, cool that mustache link, I’m gonna go check out these libraries he referenced.

Show 2 more comments

1 answer

2


I managed to solve using the Smart Format., I don’t know if it’s a good library, but right now I’m taking what I need.

var pessoa = new Pessoa()
{
    Documento = new Documento()
    {
        Numero = 12345,
        Tipo = "RG"
    },
    Idade = 20,
    Nome = "Papai Noel",
    Codigo = 1,
};

string expressao = "Pessoa/{Documento.Tipo}";
string texto = string.Empty;

texto = Smart.Format(expressao, pessoa);
Console.WriteLine(texto);
  • This library does not solve the problem of your question either?

  • @Leandroangelo, solve yes. mounted the string as I wanted.

Browser other questions tagged

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