Is it possible to include a C# variable in a string variable without using a concatenator?

前端 未结 14 1802
遥遥无期
遥遥无期 2021-02-14 07:02

Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In

相关标签:
14条回答
  • 2021-02-14 07:49

    No, unfortunately C# is not PHP.
    On the bright side though, C# is not PHP.

    0 讨论(0)
  • 2021-02-14 07:50

    Almost, with a small extension method.

    static class StringExtensions
    {
        public static string PHPIt<T>(this string s, T values, string prefix = "$")
        {
            var sb = new StringBuilder(s);
            foreach(var p in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                sb = sb.Replace(prefix + p.Name, p.GetValue(values, null).ToString());
            }
            return sb.ToString();
        }
    }
    

    And now we can write:

    string foo = "Bar";
    int cool = 2;
    
    var result = "This is a string $foo with $cool variables"
                 .PHPIt(new { 
                        foo, 
                        cool 
                    });
    
    //result == "This is a string Bar with 2 variables"
    
    0 讨论(0)
提交回复
热议问题